ExcelUtil.java 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  1. package com.ruoyi.common.utils.poi;
  2. import com.ruoyi.common.annotation.Excel;
  3. import com.ruoyi.common.annotation.Excel.ColumnType;
  4. import com.ruoyi.common.annotation.Excel.Type;
  5. import com.ruoyi.common.annotation.Excels;
  6. import com.ruoyi.common.config.RuoYiConfig;
  7. import com.ruoyi.common.core.domain.AjaxResult;
  8. import com.ruoyi.common.core.text.Convert;
  9. import com.ruoyi.common.exception.UtilException;
  10. import com.ruoyi.common.utils.DateUtils;
  11. import com.ruoyi.common.utils.DictUtils;
  12. import com.ruoyi.common.utils.StringUtils;
  13. import com.ruoyi.common.utils.file.FileTypeUtils;
  14. import com.ruoyi.common.utils.file.FileUtils;
  15. import com.ruoyi.common.utils.file.ImageUtils;
  16. import com.ruoyi.common.utils.reflect.ReflectUtils;
  17. import org.apache.commons.lang3.ArrayUtils;
  18. import org.apache.commons.lang3.RegExUtils;
  19. import org.apache.commons.lang3.reflect.FieldUtils;
  20. import org.apache.poi.hssf.usermodel.*;
  21. import org.apache.poi.ooxml.POIXMLDocumentPart;
  22. import org.apache.poi.ss.usermodel.*;
  23. import org.apache.poi.ss.util.CellRangeAddress;
  24. import org.apache.poi.ss.util.CellRangeAddressList;
  25. import org.apache.poi.util.IOUtils;
  26. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  27. import org.apache.poi.xssf.usermodel.*;
  28. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
  29. import org.slf4j.Logger;
  30. import org.slf4j.LoggerFactory;
  31. import javax.servlet.http.HttpServletResponse;
  32. import java.io.*;
  33. import java.lang.reflect.Field;
  34. import java.lang.reflect.Method;
  35. import java.lang.reflect.ParameterizedType;
  36. import java.math.BigDecimal;
  37. import java.text.DecimalFormat;
  38. import java.time.LocalDate;
  39. import java.time.LocalDateTime;
  40. import java.util.*;
  41. import java.util.stream.Collectors;
  42. /**
  43. * Excel相关处理
  44. *
  45. * @author ruoyi
  46. */
  47. public class ExcelUtil<T>
  48. {
  49. private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
  50. public static final String FORMULA_REGEX_STR = "=|-|\\+|@";
  51. public static final String[] FORMULA_STR = { "=", "-", "+", "@" };
  52. /**
  53. * 导出Excel时,如果有大量的字典数据,就会有大量的查询redis(打开、关闭),导致特别慢。
  54. * 于是使用map存储字典数据,相同的key就不需要再次去查询redis
  55. */
  56. public Map<String,String> sysDictMap = new HashMap<String,String>();
  57. /**
  58. * Excel sheet最大行数,默认65536
  59. */
  60. public static final int sheetSize = 65536;
  61. /**
  62. * 工作表名称
  63. */
  64. private String sheetName;
  65. /**
  66. * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
  67. */
  68. private Type type;
  69. /**
  70. * 工作薄对象
  71. */
  72. private Workbook wb;
  73. /**
  74. * 工作表对象
  75. */
  76. private Sheet sheet;
  77. /**
  78. * 样式列表
  79. */
  80. private Map<String, CellStyle> styles;
  81. /**
  82. * 导入导出数据列表
  83. */
  84. private List<T> list;
  85. /**
  86. * 注解列表
  87. */
  88. private List<Object[]> fields;
  89. /**
  90. * 当前行号
  91. */
  92. private int rownum;
  93. /**
  94. * 标题
  95. */
  96. private String title;
  97. /**
  98. * 最大高度
  99. */
  100. private short maxHeight;
  101. /**
  102. * 合并后最后行数
  103. */
  104. private int subMergedLastRowNum = 0;
  105. /**
  106. * 合并后开始行数
  107. */
  108. private int subMergedFirstRowNum = 1;
  109. /**
  110. * 对象的子列表方法
  111. */
  112. private Method subMethod;
  113. /**
  114. * 对象的子列表属性
  115. */
  116. private List<Field> subFields;
  117. /**
  118. * 统计列表
  119. */
  120. private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
  121. /**
  122. * 数字格式
  123. */
  124. private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
  125. /**
  126. * 实体对象
  127. */
  128. public Class<T> clazz;
  129. /**
  130. * 需要排除列属性
  131. */
  132. public String[] excludeFields;
  133. public ExcelUtil(Class<T> clazz)
  134. {
  135. this.clazz = clazz;
  136. }
  137. /**
  138. * 隐藏Excel中列属性
  139. *
  140. * @param fields 列属性名 示例[单个"name"/多个"id","name"]
  141. * @throws Exception
  142. */
  143. public void hideColumn(String... fields)
  144. {
  145. this.excludeFields = fields;
  146. }
  147. public void init(List<T> list, String sheetName, String title, Type type)
  148. {
  149. if (list == null)
  150. {
  151. list = new ArrayList<T>();
  152. }
  153. this.list = list;
  154. this.sheetName = sheetName;
  155. this.type = type;
  156. this.title = title;
  157. createExcelField();
  158. createWorkbook();
  159. createTitle();
  160. createSubHead();
  161. }
  162. /**
  163. * 创建excel第一行标题
  164. */
  165. public void createTitle()
  166. {
  167. if (StringUtils.isNotEmpty(title))
  168. {
  169. subMergedFirstRowNum++;
  170. subMergedLastRowNum++;
  171. int titleLastCol = this.fields.size() - 1;
  172. if (isSubList())
  173. {
  174. titleLastCol = titleLastCol + subFields.size() - 1;
  175. }
  176. Row titleRow = sheet.createRow(rownum == 0 ? rownum++ : 0);
  177. titleRow.setHeightInPoints(30);
  178. Cell titleCell = titleRow.createCell(0);
  179. titleCell.setCellStyle(styles.get("title"));
  180. titleCell.setCellValue(title);
  181. sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), titleLastCol));
  182. }
  183. }
  184. /**
  185. * 创建对象的子列表名称
  186. */
  187. public void createSubHead()
  188. {
  189. if (isSubList())
  190. {
  191. subMergedFirstRowNum++;
  192. subMergedLastRowNum++;
  193. Row subRow = sheet.createRow(rownum);
  194. int excelNum = 0;
  195. for (Object[] objects : fields)
  196. {
  197. Excel attr = (Excel) objects[1];
  198. Cell headCell1 = subRow.createCell(excelNum);
  199. headCell1.setCellValue(attr.name());
  200. headCell1.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
  201. excelNum++;
  202. }
  203. int headFirstRow = excelNum - 1;
  204. int headLastRow = headFirstRow + subFields.size() - 1;
  205. if (headLastRow > headFirstRow)
  206. {
  207. sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, headFirstRow, headLastRow));
  208. }
  209. rownum++;
  210. }
  211. }
  212. /**
  213. * 对excel表单默认第一个索引名转换成list
  214. *
  215. * @param is 输入流
  216. * @return 转换后集合
  217. */
  218. public List<T> importExcel(InputStream is) throws Exception
  219. {
  220. return importExcel(is, 0);
  221. }
  222. /**
  223. * 对excel表单默认第一个索引名转换成list
  224. *
  225. * @param is 输入流
  226. * @param titleNum 标题占用行数
  227. * @return 转换后集合
  228. */
  229. public List<T> importExcel(InputStream is, int titleNum) throws Exception
  230. {
  231. return importExcel(StringUtils.EMPTY, is, titleNum);
  232. }
  233. /**
  234. * 对excel表单指定表格索引名转换成list
  235. *
  236. * @param sheetName 表格索引名
  237. * @param titleNum 标题占用行数
  238. * @param is 输入流
  239. * @return 转换后集合
  240. */
  241. public List<T> importExcel(String sheetName, InputStream is, int titleNum) throws Exception
  242. {
  243. this.type = Type.IMPORT;
  244. this.wb = WorkbookFactory.create(is);
  245. List<T> list = new ArrayList<T>();
  246. // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
  247. Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0);
  248. if (sheet == null)
  249. {
  250. throw new IOException("文件sheet不存在");
  251. }
  252. boolean isXSSFWorkbook = !(wb instanceof HSSFWorkbook);
  253. Map<String, PictureData> pictures;
  254. if (isXSSFWorkbook)
  255. {
  256. pictures = getSheetPictures07((XSSFSheet) sheet, (XSSFWorkbook) wb);
  257. }
  258. else
  259. {
  260. pictures = getSheetPictures03((HSSFSheet) sheet, (HSSFWorkbook) wb);
  261. }
  262. // 获取最后一个非空行的行下标,比如总行数为n,则返回的为n-1
  263. int rows = sheet.getLastRowNum();
  264. if (rows > 0)
  265. {
  266. // 定义一个map用于存放excel列的序号和field.
  267. Map<String, Integer> cellMap = new HashMap<String, Integer>();
  268. // 获取表头
  269. Row heard = sheet.getRow(titleNum);
  270. for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
  271. {
  272. Cell cell = heard.getCell(i);
  273. if (StringUtils.isNotNull(cell))
  274. {
  275. String value = this.getCellValue(heard, i).toString();
  276. cellMap.put(value, i);
  277. }
  278. else
  279. {
  280. cellMap.put(null, i);
  281. }
  282. }
  283. // 有数据时才处理 得到类的所有field.
  284. List<Object[]> fields = this.getFields();
  285. Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>();
  286. for (Object[] objects : fields)
  287. {
  288. Excel attr = (Excel) objects[1];
  289. Integer column = cellMap.get(attr.name());
  290. if (column != null)
  291. {
  292. fieldsMap.put(column, objects);
  293. }
  294. }
  295. for (int i = titleNum + 1; i <= rows; i++)
  296. {
  297. // 从第2行开始取数据,默认第一行是表头.
  298. Row row = sheet.getRow(i);
  299. // 判断当前行是否是空行
  300. if (isRowEmpty(row))
  301. {
  302. continue;
  303. }
  304. T entity = null;
  305. for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet())
  306. {
  307. Object val = this.getCellValue(row, entry.getKey());
  308. // 如果不存在实例则新建.
  309. entity = (entity == null ? clazz.newInstance() : entity);
  310. // 从map中得到对应列的field.
  311. Field field = (Field) entry.getValue()[0];
  312. Excel attr = (Excel) entry.getValue()[1];
  313. // 取得类型,并根据对象类型设置值.
  314. Class<?> fieldType = field.getType();
  315. if (String.class == fieldType)
  316. {
  317. String s = Convert.toStr(val);
  318. if (StringUtils.endsWith(s, ".0"))
  319. {
  320. val = StringUtils.substringBefore(s, ".0");
  321. }
  322. else
  323. {
  324. String dateFormat = field.getAnnotation(Excel.class).dateFormat();
  325. if (StringUtils.isNotEmpty(dateFormat))
  326. {
  327. val = parseDateToStr(dateFormat, val);
  328. }
  329. else
  330. {
  331. val = Convert.toStr(val);
  332. }
  333. }
  334. }
  335. else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
  336. {
  337. val = Convert.toInt(val);
  338. }
  339. else if ((Long.TYPE == fieldType || Long.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
  340. {
  341. val = Convert.toLong(val);
  342. }
  343. else if (Double.TYPE == fieldType || Double.class == fieldType)
  344. {
  345. val = Convert.toDouble(val);
  346. }
  347. else if (Float.TYPE == fieldType || Float.class == fieldType)
  348. {
  349. val = Convert.toFloat(val);
  350. }
  351. else if (BigDecimal.class == fieldType)
  352. {
  353. val = Convert.toBigDecimal(val);
  354. }
  355. else if (Date.class == fieldType)
  356. {
  357. if (val instanceof String)
  358. {
  359. val = DateUtils.parseDate(val);
  360. }
  361. else if (val instanceof Double)
  362. {
  363. val = DateUtil.getJavaDate((Double) val);
  364. }
  365. }
  366. else if (Boolean.TYPE == fieldType || Boolean.class == fieldType)
  367. {
  368. val = Convert.toBool(val, false);
  369. }
  370. if (StringUtils.isNotNull(fieldType))
  371. {
  372. String propertyName = field.getName();
  373. if (StringUtils.isNotEmpty(attr.targetAttr()))
  374. {
  375. propertyName = field.getName() + "." + attr.targetAttr();
  376. }
  377. else if (StringUtils.isNotEmpty(attr.readConverterExp()))
  378. {
  379. val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
  380. }
  381. else if (StringUtils.isNotEmpty(attr.dictType()))
  382. {
  383. val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
  384. }
  385. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  386. {
  387. val = dataFormatHandlerAdapter(val, attr);
  388. }
  389. else if (ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures))
  390. {
  391. PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey());
  392. if (image == null)
  393. {
  394. val = "";
  395. }
  396. else
  397. {
  398. byte[] data = image.getData();
  399. val = FileUtils.writeImportBytes(data);
  400. }
  401. }
  402. ReflectUtils.invokeSetter(entity, propertyName, val);
  403. }
  404. }
  405. list.add(entity);
  406. }
  407. }
  408. return list;
  409. }
  410. /**
  411. * 对list数据源将其里面的数据导入到excel表单
  412. *
  413. * @param list 导出数据集合
  414. * @param sheetName 工作表的名称
  415. * @return 结果
  416. */
  417. public AjaxResult exportExcel(List<T> list, String sheetName)
  418. {
  419. return exportExcel(list, sheetName, StringUtils.EMPTY);
  420. }
  421. /**
  422. * 对list数据源将其里面的数据导入到excel表单
  423. *
  424. * @param list 导出数据集合
  425. * @param sheetName 工作表的名称
  426. * @param title 标题
  427. * @return 结果
  428. */
  429. public AjaxResult exportExcel(List<T> list, String sheetName, String title)
  430. {
  431. this.init(list, sheetName, title, Type.EXPORT);
  432. return exportExcel();
  433. }
  434. /**
  435. * 对list数据源将其里面的数据导入到excel表单
  436. *
  437. * @param response 返回数据
  438. * @param list 导出数据集合
  439. * @param sheetName 工作表的名称
  440. * @return 结果
  441. */
  442. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName)
  443. {
  444. exportExcel(response, list, sheetName, StringUtils.EMPTY);
  445. }
  446. /**
  447. * 对list数据源将其里面的数据导入到excel表单
  448. *
  449. * @param response 返回数据
  450. * @param list 导出数据集合
  451. * @param sheetName 工作表的名称
  452. * @param title 标题
  453. * @return 结果
  454. */
  455. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName, String title)
  456. {
  457. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  458. response.setCharacterEncoding("utf-8");
  459. this.init(list, sheetName, title, Type.EXPORT);
  460. exportExcel(response);
  461. }
  462. /**
  463. * 对list数据源将其里面的数据导入到excel表单
  464. *
  465. * @param sheetName 工作表的名称
  466. * @return 结果
  467. */
  468. public AjaxResult importTemplateExcel(String sheetName)
  469. {
  470. return importTemplateExcel(sheetName, StringUtils.EMPTY);
  471. }
  472. /**
  473. * 对list数据源将其里面的数据导入到excel表单
  474. *
  475. * @param sheetName 工作表的名称
  476. * @param title 标题
  477. * @return 结果
  478. */
  479. public AjaxResult importTemplateExcel(String sheetName, String title)
  480. {
  481. this.init(null, sheetName, title, Type.IMPORT);
  482. return exportExcel();
  483. }
  484. /**
  485. * 对list数据源将其里面的数据导入到excel表单
  486. *
  487. * @param sheetName 工作表的名称
  488. * @return 结果
  489. */
  490. public void importTemplateExcel(HttpServletResponse response, String sheetName)
  491. {
  492. importTemplateExcel(response, sheetName, StringUtils.EMPTY);
  493. }
  494. /**
  495. * 对list数据源将其里面的数据导入到excel表单
  496. *
  497. * @param sheetName 工作表的名称
  498. * @param title 标题
  499. * @return 结果
  500. */
  501. public void importTemplateExcel(HttpServletResponse response, String sheetName, String title)
  502. {
  503. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  504. response.setCharacterEncoding("utf-8");
  505. this.init(null, sheetName, title, Type.IMPORT);
  506. exportExcel(response);
  507. }
  508. /**
  509. * 对list数据源将其里面的数据导入到excel表单
  510. *
  511. * @return 结果
  512. */
  513. public void exportExcel(HttpServletResponse response)
  514. {
  515. try
  516. {
  517. writeSheet();
  518. wb.write(response.getOutputStream());
  519. }
  520. catch (Exception e)
  521. {
  522. log.error("导出Excel异常{}", e.getMessage());
  523. }
  524. finally
  525. {
  526. IOUtils.closeQuietly(wb);
  527. }
  528. }
  529. /**
  530. * 对list数据源将其里面的数据导入到excel表单
  531. *
  532. * @return 结果
  533. */
  534. public AjaxResult exportExcel()
  535. {
  536. OutputStream out = null;
  537. try
  538. {
  539. writeSheet();
  540. String filename = encodingFilename(sheetName);
  541. out = new FileOutputStream(getAbsoluteFile(filename));
  542. wb.write(out);
  543. return AjaxResult.success(filename);
  544. }
  545. catch (Exception e)
  546. {
  547. log.error("导出Excel异常{}", e.getMessage());
  548. throw new UtilException("导出Excel失败,请联系网站管理员!");
  549. }
  550. finally
  551. {
  552. IOUtils.closeQuietly(wb);
  553. IOUtils.closeQuietly(out);
  554. }
  555. }
  556. /**
  557. * 创建写入数据到Sheet
  558. */
  559. public void writeSheet()
  560. {
  561. // 取出一共有多少个sheet.
  562. int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
  563. for (int index = 0; index < sheetNo; index++)
  564. {
  565. createSheet(sheetNo, index);
  566. // 产生一行
  567. Row row = sheet.createRow(rownum);
  568. int column = 0;
  569. // 写入各个字段的列头名称
  570. for (Object[] os : fields)
  571. {
  572. Field field = (Field) os[0];
  573. Excel excel = (Excel) os[1];
  574. if (Collection.class.isAssignableFrom(field.getType()))
  575. {
  576. for (Field subField : subFields)
  577. {
  578. Excel subExcel = subField.getAnnotation(Excel.class);
  579. this.createHeadCell(subExcel, row, column++);
  580. }
  581. }
  582. else
  583. {
  584. this.createHeadCell(excel, row, column++);
  585. }
  586. }
  587. if (Type.EXPORT.equals(type))
  588. {
  589. fillExcelData(index, row);
  590. addStatisticsRow();
  591. }
  592. }
  593. }
  594. /**
  595. * 填充excel数据
  596. *
  597. * @param index 序号
  598. * @param row 单元格行
  599. */
  600. @SuppressWarnings("unchecked")
  601. public void fillExcelData(int index, Row row)
  602. {
  603. int startNo = index * sheetSize;
  604. int endNo = Math.min(startNo + sheetSize, list.size());
  605. int rowNo = (1 + rownum) - startNo;
  606. for (int i = startNo; i < endNo; i++)
  607. {
  608. rowNo = isSubList() ? (i > 1 ? rowNo + 1 : rowNo + i) : i + 1 + rownum - startNo;
  609. row = sheet.createRow(rowNo);
  610. // 得到导出对象.
  611. T vo = (T) list.get(i);
  612. Collection<?> subList = null;
  613. if (isSubList())
  614. {
  615. if (isSubListValue(vo))
  616. {
  617. subList = getListCellValue(vo);
  618. subMergedLastRowNum = subMergedLastRowNum + subList.size();
  619. }
  620. else
  621. {
  622. subMergedFirstRowNum++;
  623. subMergedLastRowNum++;
  624. }
  625. }
  626. int column = 0;
  627. for (Object[] os : fields)
  628. {
  629. Field field = (Field) os[0];
  630. Excel excel = (Excel) os[1];
  631. if (Collection.class.isAssignableFrom(field.getType()) && StringUtils.isNotNull(subList))
  632. {
  633. boolean subFirst = false;
  634. for (Object obj : subList)
  635. {
  636. if (subFirst)
  637. {
  638. rowNo++;
  639. row = sheet.createRow(rowNo);
  640. }
  641. List<Field> subFields = FieldUtils.getFieldsListWithAnnotation(obj.getClass(), Excel.class);
  642. int subIndex = 0;
  643. for (Field subField : subFields)
  644. {
  645. if (subField.isAnnotationPresent(Excel.class))
  646. {
  647. subField.setAccessible(true);
  648. Excel attr = subField.getAnnotation(Excel.class);
  649. this.addCell(attr, row, (T) obj, subField, column + subIndex);
  650. }
  651. subIndex++;
  652. }
  653. subFirst = true;
  654. }
  655. this.subMergedFirstRowNum = this.subMergedFirstRowNum + subList.size();
  656. }
  657. else
  658. {
  659. this.addCell(excel, row, vo, field, column++);
  660. }
  661. }
  662. }
  663. }
  664. /**
  665. * 创建表格样式
  666. *
  667. * @param wb 工作薄对象
  668. * @return 样式列表
  669. */
  670. private Map<String, CellStyle> createStyles(Workbook wb)
  671. {
  672. // 写入各条记录,每条记录对应excel表中的一行
  673. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  674. CellStyle style = wb.createCellStyle();
  675. style.setAlignment(HorizontalAlignment.CENTER);
  676. style.setVerticalAlignment(VerticalAlignment.CENTER);
  677. Font titleFont = wb.createFont();
  678. titleFont.setFontName("Arial");
  679. titleFont.setFontHeightInPoints((short) 16);
  680. titleFont.setBold(true);
  681. style.setFont(titleFont);
  682. styles.put("title", style);
  683. style = wb.createCellStyle();
  684. style.setAlignment(HorizontalAlignment.CENTER);
  685. style.setVerticalAlignment(VerticalAlignment.CENTER);
  686. style.setBorderRight(BorderStyle.THIN);
  687. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  688. style.setBorderLeft(BorderStyle.THIN);
  689. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  690. style.setBorderTop(BorderStyle.THIN);
  691. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  692. style.setBorderBottom(BorderStyle.THIN);
  693. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  694. Font dataFont = wb.createFont();
  695. dataFont.setFontName("Arial");
  696. dataFont.setFontHeightInPoints((short) 10);
  697. style.setFont(dataFont);
  698. styles.put("data", style);
  699. style = wb.createCellStyle();
  700. style.setAlignment(HorizontalAlignment.CENTER);
  701. style.setVerticalAlignment(VerticalAlignment.CENTER);
  702. Font totalFont = wb.createFont();
  703. totalFont.setFontName("Arial");
  704. totalFont.setFontHeightInPoints((short) 10);
  705. style.setFont(totalFont);
  706. styles.put("total", style);
  707. styles.putAll(annotationHeaderStyles(wb, styles));
  708. styles.putAll(annotationDataStyles(wb));
  709. return styles;
  710. }
  711. /**
  712. * 根据Excel注解创建表格头样式
  713. *
  714. * @param wb 工作薄对象
  715. * @return 自定义样式列表
  716. */
  717. private Map<String, CellStyle> annotationHeaderStyles(Workbook wb, Map<String, CellStyle> styles)
  718. {
  719. Map<String, CellStyle> headerStyles = new HashMap<String, CellStyle>();
  720. for (Object[] os : fields)
  721. {
  722. Excel excel = (Excel) os[1];
  723. String key = StringUtils.format("header_{}_{}", excel.headerColor(), excel.headerBackgroundColor());
  724. if (!headerStyles.containsKey(key))
  725. {
  726. CellStyle style = wb.createCellStyle();
  727. style.cloneStyleFrom(styles.get("data"));
  728. style.setAlignment(HorizontalAlignment.CENTER);
  729. style.setVerticalAlignment(VerticalAlignment.CENTER);
  730. style.setFillForegroundColor(excel.headerBackgroundColor().index);
  731. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  732. Font headerFont = wb.createFont();
  733. headerFont.setFontName("Arial");
  734. headerFont.setFontHeightInPoints((short) 10);
  735. headerFont.setBold(true);
  736. headerFont.setColor(excel.headerColor().index);
  737. style.setFont(headerFont);
  738. headerStyles.put(key, style);
  739. }
  740. }
  741. return headerStyles;
  742. }
  743. /**
  744. * 根据Excel注解创建表格列样式
  745. *
  746. * @param wb 工作薄对象
  747. * @return 自定义样式列表
  748. */
  749. private Map<String, CellStyle> annotationDataStyles(Workbook wb)
  750. {
  751. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  752. for (Object[] os : fields)
  753. {
  754. Excel excel = (Excel) os[1];
  755. String key = StringUtils.format("data_{}_{}_{}", excel.align(), excel.color(), excel.backgroundColor());
  756. if (!styles.containsKey(key))
  757. {
  758. CellStyle style = wb.createCellStyle();
  759. style.setAlignment(excel.align());
  760. style.setVerticalAlignment(VerticalAlignment.CENTER);
  761. style.setBorderRight(BorderStyle.THIN);
  762. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  763. style.setBorderLeft(BorderStyle.THIN);
  764. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  765. style.setBorderTop(BorderStyle.THIN);
  766. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  767. style.setBorderBottom(BorderStyle.THIN);
  768. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  769. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  770. style.setFillForegroundColor(excel.backgroundColor().getIndex());
  771. Font dataFont = wb.createFont();
  772. dataFont.setFontName("Arial");
  773. dataFont.setFontHeightInPoints((short) 10);
  774. dataFont.setColor(excel.color().index);
  775. style.setFont(dataFont);
  776. styles.put(key, style);
  777. }
  778. }
  779. return styles;
  780. }
  781. /**
  782. * 创建单元格
  783. */
  784. public Cell createHeadCell(Excel attr, Row row, int column)
  785. {
  786. // 创建列
  787. Cell cell = row.createCell(column);
  788. // 写入列信息
  789. cell.setCellValue(attr.name());
  790. setDataValidation(attr, row, column);
  791. cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
  792. if (isSubList())
  793. {
  794. // 填充默认样式,防止合并单元格样式失效
  795. sheet.setDefaultColumnStyle(column, styles.get(StringUtils.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor())));
  796. if (attr.needMerge())
  797. {
  798. sheet.addMergedRegion(new CellRangeAddress(rownum - 1, rownum, column, column));
  799. }
  800. }
  801. return cell;
  802. }
  803. /**
  804. * 设置单元格信息
  805. *
  806. * @param value 单元格值
  807. * @param attr 注解相关
  808. * @param cell 单元格信息
  809. */
  810. public void setCellVo(Object value, Excel attr, Cell cell)
  811. {
  812. if (ColumnType.STRING == attr.cellType())
  813. {
  814. String cellValue = Convert.toStr(value);
  815. // 对于任何以表达式触发字符 =-+@开头的单元格,直接使用tab字符作为前缀,防止CSV注入。
  816. if (StringUtils.startsWithAny(cellValue, FORMULA_STR))
  817. {
  818. cellValue = RegExUtils.replaceFirst(cellValue, FORMULA_REGEX_STR, "\t$0");
  819. }
  820. if (value instanceof Collection && StringUtils.equals("[]", cellValue))
  821. {
  822. cellValue = StringUtils.EMPTY;
  823. }
  824. cell.setCellValue(StringUtils.isNull(cellValue) ? attr.defaultValue() : cellValue + attr.suffix());
  825. }
  826. else if (ColumnType.NUMERIC == attr.cellType())
  827. {
  828. if (StringUtils.isNotNull(value))
  829. {
  830. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  831. }
  832. }
  833. else if (ColumnType.IMAGE == attr.cellType())
  834. {
  835. ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
  836. String imagePath = Convert.toStr(value);
  837. if (StringUtils.isNotEmpty(imagePath))
  838. {
  839. byte[] data = ImageUtils.getImage(imagePath);
  840. getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
  841. cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
  842. }
  843. }
  844. }
  845. /**
  846. * 获取画布
  847. */
  848. public static Drawing<?> getDrawingPatriarch(Sheet sheet)
  849. {
  850. if (sheet.getDrawingPatriarch() == null)
  851. {
  852. sheet.createDrawingPatriarch();
  853. }
  854. return sheet.getDrawingPatriarch();
  855. }
  856. /**
  857. * 获取图片类型,设置图片插入类型
  858. */
  859. public int getImageType(byte[] value)
  860. {
  861. String type = FileTypeUtils.getFileExtendName(value);
  862. if ("JPG".equalsIgnoreCase(type))
  863. {
  864. return Workbook.PICTURE_TYPE_JPEG;
  865. }
  866. else if ("PNG".equalsIgnoreCase(type))
  867. {
  868. return Workbook.PICTURE_TYPE_PNG;
  869. }
  870. return Workbook.PICTURE_TYPE_JPEG;
  871. }
  872. /**
  873. * 创建表格样式
  874. */
  875. public void setDataValidation(Excel attr, Row row, int column)
  876. {
  877. if (attr.name().indexOf("注:") >= 0)
  878. {
  879. sheet.setColumnWidth(column, 6000);
  880. }
  881. else
  882. {
  883. // 设置列宽
  884. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  885. }
  886. if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0)
  887. {
  888. if (attr.combo().length > 15 || StringUtils.join(attr.combo()).length() > 255)
  889. {
  890. // 如果下拉数大于15或字符串长度大于255,则使用一个新sheet存储,避免生成的模板下拉值获取不到
  891. setXSSFValidationWithHidden(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
  892. }
  893. else
  894. {
  895. // 提示信息或只能选择不能输入的列内容.
  896. setPromptOrValidation(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
  897. }
  898. }
  899. }
  900. /**
  901. * 添加单元格
  902. */
  903. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  904. {
  905. Cell cell = null;
  906. try
  907. {
  908. // 设置行高
  909. row.setHeight(maxHeight);
  910. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  911. if (attr.isExport())
  912. {
  913. // 创建cell
  914. cell = row.createCell(column);
  915. if (isSubListValue(vo) && getListCellValue(vo).size() > 1 && attr.needMerge())
  916. {
  917. CellRangeAddress cellAddress = new CellRangeAddress(subMergedFirstRowNum, subMergedLastRowNum, column, column);
  918. sheet.addMergedRegion(cellAddress);
  919. }
  920. cell.setCellStyle(styles.get(StringUtils.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor())));
  921. // 用于读取对象中的属性
  922. Object value = getTargetValue(vo, field, attr);
  923. String dateFormat = attr.dateFormat();
  924. String readConverterExp = attr.readConverterExp();
  925. String separator = attr.separator();
  926. String dictType = attr.dictType();
  927. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  928. {
  929. cell.setCellValue(parseDateToStr(dateFormat, value));
  930. }
  931. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  932. {
  933. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  934. }
  935. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  936. {
  937. if (!sysDictMap.containsKey(dictType+value)){
  938. String lable = convertDictByExp(Convert.toStr(value), dictType, separator);
  939. sysDictMap.put(dictType+value,lable);
  940. }
  941. cell.setCellValue(sysDictMap.get(dictType+value));
  942. }
  943. else if (value instanceof BigDecimal && -1 != attr.scale())
  944. {
  945. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).doubleValue());
  946. }
  947. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  948. {
  949. cell.setCellValue(dataFormatHandlerAdapter(value, attr));
  950. }
  951. else
  952. {
  953. // 设置列类型
  954. setCellVo(value, attr, cell);
  955. }
  956. addStatisticsData(column, Convert.toStr(value), attr);
  957. }
  958. }
  959. catch (Exception e)
  960. {
  961. log.error("导出Excel失败{}", e);
  962. }
  963. return cell;
  964. }
  965. /**
  966. * 设置 POI XSSFSheet 单元格提示或选择框
  967. *
  968. * @param sheet 表单
  969. * @param textlist 下拉框显示的内容
  970. * @param promptContent 提示内容
  971. * @param firstRow 开始行
  972. * @param endRow 结束行
  973. * @param firstCol 开始列
  974. * @param endCol 结束列
  975. */
  976. public void setPromptOrValidation(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow,
  977. int firstCol, int endCol)
  978. {
  979. DataValidationHelper helper = sheet.getDataValidationHelper();
  980. DataValidationConstraint constraint = textlist.length > 0 ? helper.createExplicitListConstraint(textlist) : helper.createCustomConstraint("DD1");
  981. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  982. DataValidation dataValidation = helper.createValidation(constraint, regions);
  983. if (StringUtils.isNotEmpty(promptContent))
  984. {
  985. // 如果设置了提示信息则鼠标放上去提示
  986. dataValidation.createPromptBox("", promptContent);
  987. dataValidation.setShowPromptBox(true);
  988. }
  989. // 处理Excel兼容性问题
  990. if (dataValidation instanceof XSSFDataValidation)
  991. {
  992. dataValidation.setSuppressDropDownArrow(true);
  993. dataValidation.setShowErrorBox(true);
  994. }
  995. else
  996. {
  997. dataValidation.setSuppressDropDownArrow(false);
  998. }
  999. sheet.addValidationData(dataValidation);
  1000. }
  1001. /**
  1002. * 设置某些列的值只能输入预制的数据,显示下拉框(兼容超出一定数量的下拉框).
  1003. *
  1004. * @param sheet 要设置的sheet.
  1005. * @param textlist 下拉框显示的内容
  1006. * @param promptContent 提示内容
  1007. * @param firstRow 开始行
  1008. * @param endRow 结束行
  1009. * @param firstCol 开始列
  1010. * @param endCol 结束列
  1011. */
  1012. public void setXSSFValidationWithHidden(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow, int firstCol, int endCol)
  1013. {
  1014. String hideSheetName = "combo_" + firstCol + "_" + endCol;
  1015. Sheet hideSheet = wb.createSheet(hideSheetName); // 用于存储 下拉菜单数据
  1016. for (int i = 0; i < textlist.length; i++)
  1017. {
  1018. hideSheet.createRow(i).createCell(0).setCellValue(textlist[i]);
  1019. }
  1020. // 创建名称,可被其他单元格引用
  1021. Name name = wb.createName();
  1022. name.setNameName(hideSheetName + "_data");
  1023. name.setRefersToFormula(hideSheetName + "!$A$1:$A$" + textlist.length);
  1024. DataValidationHelper helper = sheet.getDataValidationHelper();
  1025. // 加载下拉列表内容
  1026. DataValidationConstraint constraint = helper.createFormulaListConstraint(hideSheetName + "_data");
  1027. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  1028. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  1029. // 数据有效性对象
  1030. DataValidation dataValidation = helper.createValidation(constraint, regions);
  1031. if (StringUtils.isNotEmpty(promptContent))
  1032. {
  1033. // 如果设置了提示信息则鼠标放上去提示
  1034. dataValidation.createPromptBox("", promptContent);
  1035. dataValidation.setShowPromptBox(true);
  1036. }
  1037. // 处理Excel兼容性问题
  1038. if (dataValidation instanceof XSSFDataValidation)
  1039. {
  1040. dataValidation.setSuppressDropDownArrow(true);
  1041. dataValidation.setShowErrorBox(true);
  1042. }
  1043. else
  1044. {
  1045. dataValidation.setSuppressDropDownArrow(false);
  1046. }
  1047. sheet.addValidationData(dataValidation);
  1048. // 设置hiddenSheet隐藏
  1049. wb.setSheetHidden(wb.getSheetIndex(hideSheet), true);
  1050. }
  1051. /**
  1052. * 解析导出值 0=男,1=女,2=未知
  1053. *
  1054. * @param propertyValue 参数值
  1055. * @param converterExp 翻译注解
  1056. * @param separator 分隔符
  1057. * @return 解析后值
  1058. */
  1059. public static String convertByExp(String propertyValue, String converterExp, String separator)
  1060. {
  1061. StringBuilder propertyString = new StringBuilder();
  1062. String[] convertSource = converterExp.split(",");
  1063. for (String item : convertSource)
  1064. {
  1065. String[] itemArray = item.split("=");
  1066. if (StringUtils.containsAny(propertyValue, separator))
  1067. {
  1068. for (String value : propertyValue.split(separator))
  1069. {
  1070. if (itemArray[0].equals(value))
  1071. {
  1072. propertyString.append(itemArray[1] + separator);
  1073. break;
  1074. }
  1075. }
  1076. }
  1077. else
  1078. {
  1079. if (itemArray[0].equals(propertyValue))
  1080. {
  1081. return itemArray[1];
  1082. }
  1083. }
  1084. }
  1085. return StringUtils.stripEnd(propertyString.toString(), separator);
  1086. }
  1087. /**
  1088. * 反向解析值 男=0,女=1,未知=2
  1089. *
  1090. * @param propertyValue 参数值
  1091. * @param converterExp 翻译注解
  1092. * @param separator 分隔符
  1093. * @return 解析后值
  1094. */
  1095. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  1096. {
  1097. StringBuilder propertyString = new StringBuilder();
  1098. String[] convertSource = converterExp.split(",");
  1099. for (String item : convertSource)
  1100. {
  1101. String[] itemArray = item.split("=");
  1102. if (StringUtils.containsAny(propertyValue, separator))
  1103. {
  1104. for (String value : propertyValue.split(separator))
  1105. {
  1106. if (itemArray[1].equals(value))
  1107. {
  1108. propertyString.append(itemArray[0] + separator);
  1109. break;
  1110. }
  1111. }
  1112. }
  1113. else
  1114. {
  1115. if (itemArray[1].equals(propertyValue))
  1116. {
  1117. return itemArray[0];
  1118. }
  1119. }
  1120. }
  1121. return StringUtils.stripEnd(propertyString.toString(), separator);
  1122. }
  1123. /**
  1124. * 解析字典值
  1125. *
  1126. * @param dictValue 字典值
  1127. * @param dictType 字典类型
  1128. * @param separator 分隔符
  1129. * @return 字典标签
  1130. */
  1131. public static String convertDictByExp(String dictValue, String dictType, String separator)
  1132. {
  1133. return DictUtils.getDictLabel(dictType, dictValue, separator);
  1134. }
  1135. /**
  1136. * 反向解析值字典值
  1137. *
  1138. * @param dictLabel 字典标签
  1139. * @param dictType 字典类型
  1140. * @param separator 分隔符
  1141. * @return 字典值
  1142. */
  1143. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  1144. {
  1145. return DictUtils.getDictValue(dictType, dictLabel, separator);
  1146. }
  1147. /**
  1148. * 数据处理器
  1149. *
  1150. * @param value 数据值
  1151. * @param excel 数据注解
  1152. * @return
  1153. */
  1154. public String dataFormatHandlerAdapter(Object value, Excel excel)
  1155. {
  1156. try
  1157. {
  1158. Object instance = excel.handler().newInstance();
  1159. Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class });
  1160. value = formatMethod.invoke(instance, value, excel.args());
  1161. }
  1162. catch (Exception e)
  1163. {
  1164. log.error("不能格式化数据 " + excel.handler(), e.getMessage());
  1165. }
  1166. return Convert.toStr(value);
  1167. }
  1168. /**
  1169. * 合计统计信息
  1170. */
  1171. private void addStatisticsData(Integer index, String text, Excel entity)
  1172. {
  1173. if (entity != null && entity.isStatistics())
  1174. {
  1175. Double temp = 0D;
  1176. if (!statistics.containsKey(index))
  1177. {
  1178. statistics.put(index, temp);
  1179. }
  1180. try
  1181. {
  1182. temp = Double.valueOf(text);
  1183. }
  1184. catch (NumberFormatException e)
  1185. {
  1186. }
  1187. statistics.put(index, statistics.get(index) + temp);
  1188. }
  1189. }
  1190. /**
  1191. * 创建统计行
  1192. */
  1193. public void addStatisticsRow()
  1194. {
  1195. if (statistics.size() > 0)
  1196. {
  1197. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  1198. Set<Integer> keys = statistics.keySet();
  1199. Cell cell = row.createCell(0);
  1200. cell.setCellStyle(styles.get("total"));
  1201. cell.setCellValue("合计");
  1202. for (Integer key : keys)
  1203. {
  1204. cell = row.createCell(key);
  1205. cell.setCellStyle(styles.get("total"));
  1206. cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  1207. }
  1208. statistics.clear();
  1209. }
  1210. }
  1211. /**
  1212. * 编码文件名
  1213. */
  1214. public String encodingFilename(String filename)
  1215. {
  1216. filename = UUID.randomUUID() + "_" + filename + ".xlsx";
  1217. return filename;
  1218. }
  1219. /**
  1220. * 获取下载路径
  1221. *
  1222. * @param filename 文件名称
  1223. */
  1224. public String getAbsoluteFile(String filename)
  1225. {
  1226. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  1227. File desc = new File(downloadPath);
  1228. if (!desc.getParentFile().exists())
  1229. {
  1230. desc.getParentFile().mkdirs();
  1231. }
  1232. return downloadPath;
  1233. }
  1234. /**
  1235. * 获取bean中的属性值
  1236. *
  1237. * @param vo 实体对象
  1238. * @param field 字段
  1239. * @param excel 注解
  1240. * @return 最终的属性值
  1241. * @throws Exception
  1242. */
  1243. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  1244. {
  1245. Object o = field.get(vo);
  1246. if (StringUtils.isNotEmpty(excel.targetAttr()))
  1247. {
  1248. String target = excel.targetAttr();
  1249. if (target.contains("."))
  1250. {
  1251. String[] targets = target.split("[.]");
  1252. for (String name : targets)
  1253. {
  1254. o = getValue(o, name);
  1255. }
  1256. }
  1257. else
  1258. {
  1259. o = getValue(o, target);
  1260. }
  1261. }
  1262. return o;
  1263. }
  1264. /**
  1265. * 以类的属性的get方法方法形式获取值
  1266. *
  1267. * @param o
  1268. * @param name
  1269. * @return value
  1270. * @throws Exception
  1271. */
  1272. private Object getValue(Object o, String name) throws Exception
  1273. {
  1274. if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name))
  1275. {
  1276. Class<?> clazz = o.getClass();
  1277. Field field = clazz.getDeclaredField(name);
  1278. field.setAccessible(true);
  1279. o = field.get(o);
  1280. }
  1281. return o;
  1282. }
  1283. /**
  1284. * 得到所有定义字段
  1285. */
  1286. private void createExcelField()
  1287. {
  1288. this.fields = getFields();
  1289. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  1290. this.maxHeight = getRowHeight();
  1291. }
  1292. /**
  1293. * 获取字段注解信息
  1294. */
  1295. public List<Object[]> getFields()
  1296. {
  1297. List<Object[]> fields = new ArrayList<Object[]>();
  1298. List<Field> tempFields = new ArrayList<>();
  1299. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  1300. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  1301. for (Field field : tempFields)
  1302. {
  1303. if (!ArrayUtils.contains(this.excludeFields, field.getName()))
  1304. {
  1305. // 单注解
  1306. if (field.isAnnotationPresent(Excel.class))
  1307. {
  1308. Excel attr = field.getAnnotation(Excel.class);
  1309. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1310. {
  1311. field.setAccessible(true);
  1312. fields.add(new Object[] { field, attr });
  1313. }
  1314. if (Collection.class.isAssignableFrom(field.getType()))
  1315. {
  1316. subMethod = getSubMethod(field.getName(), clazz);
  1317. ParameterizedType pt = (ParameterizedType) field.getGenericType();
  1318. Class<?> subClass = (Class<?>) pt.getActualTypeArguments()[0];
  1319. this.subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class);
  1320. }
  1321. }
  1322. // 多注解
  1323. if (field.isAnnotationPresent(Excels.class))
  1324. {
  1325. Excels attrs = field.getAnnotation(Excels.class);
  1326. Excel[] excels = attrs.value();
  1327. for (Excel attr : excels)
  1328. {
  1329. if (!ArrayUtils.contains(this.excludeFields, field.getName() + "." + attr.targetAttr())
  1330. && (attr != null && (attr.type() == Type.ALL || attr.type() == type)))
  1331. {
  1332. field.setAccessible(true);
  1333. fields.add(new Object[] { field, attr });
  1334. }
  1335. }
  1336. }
  1337. }
  1338. }
  1339. return fields;
  1340. }
  1341. /**
  1342. * 根据注解获取最大行高
  1343. */
  1344. public short getRowHeight()
  1345. {
  1346. double maxHeight = 0;
  1347. for (Object[] os : this.fields)
  1348. {
  1349. Excel excel = (Excel) os[1];
  1350. maxHeight = Math.max(maxHeight, excel.height());
  1351. }
  1352. return (short) (maxHeight * 20);
  1353. }
  1354. /**
  1355. * 创建一个工作簿
  1356. */
  1357. public void createWorkbook()
  1358. {
  1359. this.wb = new SXSSFWorkbook(500);
  1360. this.sheet = wb.createSheet();
  1361. wb.setSheetName(0, sheetName);
  1362. this.styles = createStyles(wb);
  1363. }
  1364. /**
  1365. * 创建工作表
  1366. *
  1367. * @param sheetNo sheet数量
  1368. * @param index 序号
  1369. */
  1370. public void createSheet(int sheetNo, int index)
  1371. {
  1372. // 设置工作表的名称.
  1373. if (sheetNo > 1 && index > 0)
  1374. {
  1375. this.sheet = wb.createSheet();
  1376. this.createTitle();
  1377. wb.setSheetName(index, sheetName + index);
  1378. }
  1379. }
  1380. /**
  1381. * 获取单元格值
  1382. *
  1383. * @param row 获取的行
  1384. * @param column 获取单元格列号
  1385. * @return 单元格值
  1386. */
  1387. public Object getCellValue(Row row, int column)
  1388. {
  1389. if (row == null)
  1390. {
  1391. return row;
  1392. }
  1393. Object val = "";
  1394. try
  1395. {
  1396. Cell cell = row.getCell(column);
  1397. if (StringUtils.isNotNull(cell))
  1398. {
  1399. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  1400. {
  1401. val = cell.getNumericCellValue();
  1402. if (DateUtil.isCellDateFormatted(cell))
  1403. {
  1404. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  1405. }
  1406. else
  1407. {
  1408. if ((Double) val % 1 != 0)
  1409. {
  1410. val = new BigDecimal(val.toString());
  1411. }
  1412. else
  1413. {
  1414. val = new DecimalFormat("0").format(val);
  1415. }
  1416. }
  1417. }
  1418. else if (cell.getCellType() == CellType.STRING)
  1419. {
  1420. val = cell.getStringCellValue();
  1421. }
  1422. else if (cell.getCellType() == CellType.BOOLEAN)
  1423. {
  1424. val = cell.getBooleanCellValue();
  1425. }
  1426. else if (cell.getCellType() == CellType.ERROR)
  1427. {
  1428. val = cell.getErrorCellValue();
  1429. }
  1430. }
  1431. }
  1432. catch (Exception e)
  1433. {
  1434. return val;
  1435. }
  1436. return val;
  1437. }
  1438. /**
  1439. * 判断是否是空行
  1440. *
  1441. * @param row 判断的行
  1442. * @return
  1443. */
  1444. private boolean isRowEmpty(Row row)
  1445. {
  1446. if (row == null)
  1447. {
  1448. return true;
  1449. }
  1450. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
  1451. {
  1452. Cell cell = row.getCell(i);
  1453. if (cell != null && cell.getCellType() != CellType.BLANK)
  1454. {
  1455. return false;
  1456. }
  1457. }
  1458. return true;
  1459. }
  1460. /**
  1461. * 获取Excel2003图片
  1462. *
  1463. * @param sheet 当前sheet对象
  1464. * @param workbook 工作簿对象
  1465. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1466. */
  1467. public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook)
  1468. {
  1469. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1470. List<HSSFPictureData> pictures = workbook.getAllPictures();
  1471. if (!pictures.isEmpty())
  1472. {
  1473. for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
  1474. {
  1475. HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
  1476. if (shape instanceof HSSFPicture)
  1477. {
  1478. HSSFPicture pic = (HSSFPicture) shape;
  1479. int pictureIndex = pic.getPictureIndex() - 1;
  1480. HSSFPictureData picData = pictures.get(pictureIndex);
  1481. String picIndex = anchor.getRow1() + "_" + anchor.getCol1();
  1482. sheetIndexPicMap.put(picIndex, picData);
  1483. }
  1484. }
  1485. return sheetIndexPicMap;
  1486. }
  1487. else
  1488. {
  1489. return sheetIndexPicMap;
  1490. }
  1491. }
  1492. /**
  1493. * 获取Excel2007图片
  1494. *
  1495. * @param sheet 当前sheet对象
  1496. * @param workbook 工作簿对象
  1497. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1498. */
  1499. public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook)
  1500. {
  1501. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1502. for (POIXMLDocumentPart dr : sheet.getRelations())
  1503. {
  1504. if (dr instanceof XSSFDrawing)
  1505. {
  1506. XSSFDrawing drawing = (XSSFDrawing) dr;
  1507. List<XSSFShape> shapes = drawing.getShapes();
  1508. for (XSSFShape shape : shapes)
  1509. {
  1510. if (shape instanceof XSSFPicture)
  1511. {
  1512. XSSFPicture pic = (XSSFPicture) shape;
  1513. XSSFClientAnchor anchor = pic.getPreferredSize();
  1514. CTMarker ctMarker = anchor.getFrom();
  1515. String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
  1516. sheetIndexPicMap.put(picIndex, pic.getPictureData());
  1517. }
  1518. }
  1519. }
  1520. }
  1521. return sheetIndexPicMap;
  1522. }
  1523. /**
  1524. * 格式化不同类型的日期对象
  1525. *
  1526. * @param dateFormat 日期格式
  1527. * @param val 被格式化的日期对象
  1528. * @return 格式化后的日期字符
  1529. */
  1530. public String parseDateToStr(String dateFormat, Object val)
  1531. {
  1532. if (val == null)
  1533. {
  1534. return "";
  1535. }
  1536. String str;
  1537. if (val instanceof Date)
  1538. {
  1539. str = DateUtils.parseDateToStr(dateFormat, (Date) val);
  1540. }
  1541. else if (val instanceof LocalDateTime)
  1542. {
  1543. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDateTime) val));
  1544. }
  1545. else if (val instanceof LocalDate)
  1546. {
  1547. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDate) val));
  1548. }
  1549. else
  1550. {
  1551. str = val.toString();
  1552. }
  1553. return str;
  1554. }
  1555. /**
  1556. * 是否有对象的子列表
  1557. */
  1558. public boolean isSubList()
  1559. {
  1560. return StringUtils.isNotNull(subFields) && subFields.size() > 0;
  1561. }
  1562. /**
  1563. * 是否有对象的子列表,集合不为空
  1564. */
  1565. public boolean isSubListValue(T vo)
  1566. {
  1567. return StringUtils.isNotNull(subFields) && subFields.size() > 0 && StringUtils.isNotNull(getListCellValue(vo)) && getListCellValue(vo).size() > 0;
  1568. }
  1569. /**
  1570. * 获取集合的值
  1571. */
  1572. public Collection<?> getListCellValue(Object obj)
  1573. {
  1574. Object value;
  1575. try
  1576. {
  1577. value = subMethod.invoke(obj, new Object[] {});
  1578. }
  1579. catch (Exception e)
  1580. {
  1581. return new ArrayList<Object>();
  1582. }
  1583. return (Collection<?>) value;
  1584. }
  1585. /**
  1586. * 获取对象的子列表方法
  1587. *
  1588. * @param name 名称
  1589. * @param pojoClass 类对象
  1590. * @return 子列表方法
  1591. */
  1592. public Method getSubMethod(String name, Class<?> pojoClass)
  1593. {
  1594. StringBuffer getMethodName = new StringBuffer("get");
  1595. getMethodName.append(name.substring(0, 1).toUpperCase());
  1596. getMethodName.append(name.substring(1));
  1597. Method method = null;
  1598. try
  1599. {
  1600. method = pojoClass.getMethod(getMethodName.toString(), new Class[] {});
  1601. }
  1602. catch (Exception e)
  1603. {
  1604. log.error("获取对象异常{}", e.getMessage());
  1605. }
  1606. return method;
  1607. }
  1608. }