ExcelUtil.java 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. package com.ruoyi.common.utils.poi;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.lang.reflect.Field;
  8. import java.math.BigDecimal;
  9. import java.text.DecimalFormat;
  10. import java.util.ArrayList;
  11. import java.util.Arrays;
  12. import java.util.Comparator;
  13. import java.util.Date;
  14. import java.util.HashMap;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.Set;
  18. import java.util.UUID;
  19. import java.util.stream.Collectors;
  20. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  21. import org.apache.poi.ss.usermodel.BorderStyle;
  22. import org.apache.poi.ss.usermodel.Cell;
  23. import org.apache.poi.ss.usermodel.CellStyle;
  24. import org.apache.poi.ss.usermodel.CellType;
  25. import org.apache.poi.ss.usermodel.DataValidation;
  26. import org.apache.poi.ss.usermodel.DataValidationConstraint;
  27. import org.apache.poi.ss.usermodel.DataValidationHelper;
  28. import org.apache.poi.ss.usermodel.DateUtil;
  29. import org.apache.poi.ss.usermodel.FillPatternType;
  30. import org.apache.poi.ss.usermodel.Font;
  31. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  32. import org.apache.poi.ss.usermodel.IndexedColors;
  33. import org.apache.poi.ss.usermodel.Row;
  34. import org.apache.poi.ss.usermodel.Sheet;
  35. import org.apache.poi.ss.usermodel.VerticalAlignment;
  36. import org.apache.poi.ss.usermodel.Workbook;
  37. import org.apache.poi.ss.usermodel.WorkbookFactory;
  38. import org.apache.poi.ss.util.CellRangeAddressList;
  39. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  40. import org.apache.poi.xssf.usermodel.XSSFDataValidation;
  41. import org.slf4j.Logger;
  42. import org.slf4j.LoggerFactory;
  43. import com.ruoyi.common.annotation.Excel;
  44. import com.ruoyi.common.annotation.Excel.ColumnType;
  45. import com.ruoyi.common.annotation.Excel.Type;
  46. import com.ruoyi.common.annotation.Excels;
  47. import com.ruoyi.common.config.RuoYiConfig;
  48. import com.ruoyi.common.core.domain.AjaxResult;
  49. import com.ruoyi.common.core.text.Convert;
  50. import com.ruoyi.common.exception.CustomException;
  51. import com.ruoyi.common.utils.DateUtils;
  52. import com.ruoyi.common.utils.DictUtils;
  53. import com.ruoyi.common.utils.StringUtils;
  54. import com.ruoyi.common.utils.reflect.ReflectUtils;
  55. /**
  56. * Excel相关处理
  57. *
  58. * @author ruoyi
  59. */
  60. public class ExcelUtil<T>
  61. {
  62. private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
  63. /**
  64. * Excel sheet最大行数,默认65536
  65. */
  66. public static final int sheetSize = 65536;
  67. /**
  68. * 工作表名称
  69. */
  70. private String sheetName;
  71. /**
  72. * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
  73. */
  74. private Type type;
  75. /**
  76. * 工作薄对象
  77. */
  78. private Workbook wb;
  79. /**
  80. * 工作表对象
  81. */
  82. private Sheet sheet;
  83. /**
  84. * 样式列表
  85. */
  86. private Map<String, CellStyle> styles;
  87. /**
  88. * 导入导出数据列表
  89. */
  90. private List<T> list;
  91. /**
  92. * 注解列表
  93. */
  94. private List<Object[]> fields;
  95. /**
  96. * 统计列表
  97. */
  98. private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
  99. /**
  100. * 数字格式
  101. */
  102. private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
  103. /**
  104. * 实体对象
  105. */
  106. public Class<T> clazz;
  107. public ExcelUtil(Class<T> clazz)
  108. {
  109. this.clazz = clazz;
  110. }
  111. public void init(List<T> list, String sheetName, Type type)
  112. {
  113. if (list == null)
  114. {
  115. list = new ArrayList<T>();
  116. }
  117. this.list = list;
  118. this.sheetName = sheetName;
  119. this.type = type;
  120. createExcelField();
  121. createWorkbook();
  122. }
  123. /**
  124. * 对excel表单默认第一个索引名转换成list
  125. *
  126. * @param is 输入流
  127. * @return 转换后集合
  128. */
  129. public List<T> importExcel(InputStream is) throws Exception
  130. {
  131. return importExcel(StringUtils.EMPTY, is);
  132. }
  133. /**
  134. * 对excel表单指定表格索引名转换成list
  135. *
  136. * @param sheetName 表格索引名
  137. * @param is 输入流
  138. * @return 转换后集合
  139. */
  140. public List<T> importExcel(String sheetName, InputStream is) throws Exception
  141. {
  142. this.type = Type.IMPORT;
  143. this.wb = WorkbookFactory.create(is);
  144. List<T> list = new ArrayList<T>();
  145. Sheet sheet = null;
  146. if (StringUtils.isNotEmpty(sheetName))
  147. {
  148. // 如果指定sheet名,则取指定sheet中的内容.
  149. sheet = wb.getSheet(sheetName);
  150. }
  151. else
  152. {
  153. // 如果传入的sheet名不存在则默认指向第1个sheet.
  154. sheet = wb.getSheetAt(0);
  155. }
  156. if (sheet == null)
  157. {
  158. throw new IOException("文件sheet不存在");
  159. }
  160. int rows = sheet.getPhysicalNumberOfRows();
  161. if (rows > 0)
  162. {
  163. // 定义一个map用于存放excel列的序号和field.
  164. Map<String, Integer> cellMap = new HashMap<String, Integer>();
  165. // 获取表头
  166. Row heard = sheet.getRow(0);
  167. for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
  168. {
  169. Cell cell = heard.getCell(i);
  170. if (StringUtils.isNotNull(cell))
  171. {
  172. String value = this.getCellValue(heard, i).toString();
  173. cellMap.put(value, i);
  174. }
  175. else
  176. {
  177. cellMap.put(null, i);
  178. }
  179. }
  180. // 有数据时才处理 得到类的所有field.
  181. Field[] allFields = clazz.getDeclaredFields();
  182. // 定义一个map用于存放列的序号和field.
  183. Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
  184. for (int col = 0; col < allFields.length; col++)
  185. {
  186. Field field = allFields[col];
  187. Excel attr = field.getAnnotation(Excel.class);
  188. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  189. {
  190. // 设置类的私有字段属性可访问.
  191. field.setAccessible(true);
  192. Integer column = cellMap.get(attr.name());
  193. if (column != null)
  194. {
  195. fieldsMap.put(column, field);
  196. }
  197. }
  198. }
  199. for (int i = 1; i < rows; i++)
  200. {
  201. // 从第2行开始取数据,默认第一行是表头.
  202. Row row = sheet.getRow(i);
  203. T entity = null;
  204. for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet())
  205. {
  206. Object val = this.getCellValue(row, entry.getKey());
  207. // 如果不存在实例则新建.
  208. entity = (entity == null ? clazz.newInstance() : entity);
  209. // 从map中得到对应列的field.
  210. Field field = fieldsMap.get(entry.getKey());
  211. // 取得类型,并根据对象类型设置值.
  212. Class<?> fieldType = field.getType();
  213. if (String.class == fieldType)
  214. {
  215. String s = Convert.toStr(val);
  216. if (StringUtils.endsWith(s, ".0"))
  217. {
  218. val = StringUtils.substringBefore(s, ".0");
  219. }
  220. else
  221. {
  222. val = Convert.toStr(val);
  223. }
  224. }
  225. else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType))
  226. {
  227. val = Convert.toInt(val);
  228. }
  229. else if ((Long.TYPE == fieldType) || (Long.class == fieldType))
  230. {
  231. val = Convert.toLong(val);
  232. }
  233. else if ((Double.TYPE == fieldType) || (Double.class == fieldType))
  234. {
  235. val = Convert.toDouble(val);
  236. }
  237. else if ((Float.TYPE == fieldType) || (Float.class == fieldType))
  238. {
  239. val = Convert.toFloat(val);
  240. }
  241. else if (BigDecimal.class == fieldType)
  242. {
  243. val = Convert.toBigDecimal(val);
  244. }
  245. else if (Date.class == fieldType)
  246. {
  247. if (val instanceof String)
  248. {
  249. val = DateUtils.parseDate(val);
  250. }
  251. else if (val instanceof Double)
  252. {
  253. val = DateUtil.getJavaDate((Double) val);
  254. }
  255. }
  256. if (StringUtils.isNotNull(fieldType))
  257. {
  258. Excel attr = field.getAnnotation(Excel.class);
  259. String propertyName = field.getName();
  260. if (StringUtils.isNotEmpty(attr.targetAttr()))
  261. {
  262. propertyName = field.getName() + "." + attr.targetAttr();
  263. }
  264. else if (StringUtils.isNotEmpty(attr.readConverterExp()))
  265. {
  266. val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
  267. }
  268. else if (StringUtils.isNotEmpty(attr.dictType()))
  269. {
  270. val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
  271. }
  272. ReflectUtils.invokeSetter(entity, propertyName, val);
  273. }
  274. }
  275. list.add(entity);
  276. }
  277. }
  278. return list;
  279. }
  280. /**
  281. * 对list数据源将其里面的数据导入到excel表单
  282. *
  283. * @param list 导出数据集合
  284. * @param sheetName 工作表的名称
  285. * @return 结果
  286. */
  287. public AjaxResult exportExcel(List<T> list, String sheetName)
  288. {
  289. this.init(list, sheetName, Type.EXPORT);
  290. return exportExcel();
  291. }
  292. /**
  293. * 对list数据源将其里面的数据导入到excel表单
  294. *
  295. * @param sheetName 工作表的名称
  296. * @return 结果
  297. */
  298. public AjaxResult importTemplateExcel(String sheetName)
  299. {
  300. this.init(null, sheetName, Type.IMPORT);
  301. return exportExcel();
  302. }
  303. /**
  304. * 对list数据源将其里面的数据导入到excel表单
  305. *
  306. * @return 结果
  307. */
  308. public AjaxResult exportExcel()
  309. {
  310. OutputStream out = null;
  311. try
  312. {
  313. // 取出一共有多少个sheet.
  314. double sheetNo = Math.ceil(list.size() / sheetSize);
  315. for (int index = 0; index <= sheetNo; index++)
  316. {
  317. createSheet(sheetNo, index);
  318. // 产生一行
  319. Row row = sheet.createRow(0);
  320. int column = 0;
  321. // 写入各个字段的列头名称
  322. for (Object[] os : fields)
  323. {
  324. Excel excel = (Excel) os[1];
  325. this.createCell(excel, row, column++);
  326. }
  327. if (Type.EXPORT.equals(type))
  328. {
  329. fillExcelData(index, row);
  330. addStatisticsRow();
  331. }
  332. }
  333. String filename = encodingFilename(sheetName);
  334. out = new FileOutputStream(getAbsoluteFile(filename));
  335. wb.write(out);
  336. return AjaxResult.success(filename);
  337. }
  338. catch (Exception e)
  339. {
  340. log.error("导出Excel异常{}", e.getMessage());
  341. throw new CustomException("导出Excel失败,请联系网站管理员!");
  342. }
  343. finally
  344. {
  345. if (wb != null)
  346. {
  347. try
  348. {
  349. wb.close();
  350. }
  351. catch (IOException e1)
  352. {
  353. e1.printStackTrace();
  354. }
  355. }
  356. if (out != null)
  357. {
  358. try
  359. {
  360. out.close();
  361. }
  362. catch (IOException e1)
  363. {
  364. e1.printStackTrace();
  365. }
  366. }
  367. }
  368. }
  369. /**
  370. * 填充excel数据
  371. *
  372. * @param index 序号
  373. * @param row 单元格行
  374. */
  375. public void fillExcelData(int index, Row row)
  376. {
  377. int startNo = index * sheetSize;
  378. int endNo = Math.min(startNo + sheetSize, list.size());
  379. for (int i = startNo; i < endNo; i++)
  380. {
  381. row = sheet.createRow(i + 1 - startNo);
  382. // 得到导出对象.
  383. T vo = (T) list.get(i);
  384. int column = 0;
  385. for (Object[] os : fields)
  386. {
  387. Field field = (Field) os[0];
  388. Excel excel = (Excel) os[1];
  389. // 设置实体类私有属性可访问
  390. field.setAccessible(true);
  391. this.addCell(excel, row, vo, field, column++);
  392. }
  393. }
  394. }
  395. /**
  396. * 创建表格样式
  397. *
  398. * @param wb 工作薄对象
  399. * @return 样式列表
  400. */
  401. private Map<String, CellStyle> createStyles(Workbook wb)
  402. {
  403. // 写入各条记录,每条记录对应excel表中的一行
  404. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  405. CellStyle style = wb.createCellStyle();
  406. style.setAlignment(HorizontalAlignment.CENTER);
  407. style.setVerticalAlignment(VerticalAlignment.CENTER);
  408. style.setBorderRight(BorderStyle.THIN);
  409. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  410. style.setBorderLeft(BorderStyle.THIN);
  411. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  412. style.setBorderTop(BorderStyle.THIN);
  413. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  414. style.setBorderBottom(BorderStyle.THIN);
  415. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  416. Font dataFont = wb.createFont();
  417. dataFont.setFontName("Arial");
  418. dataFont.setFontHeightInPoints((short) 10);
  419. style.setFont(dataFont);
  420. styles.put("data", style);
  421. style = wb.createCellStyle();
  422. style.cloneStyleFrom(styles.get("data"));
  423. style.setAlignment(HorizontalAlignment.CENTER);
  424. style.setVerticalAlignment(VerticalAlignment.CENTER);
  425. style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
  426. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  427. Font headerFont = wb.createFont();
  428. headerFont.setFontName("Arial");
  429. headerFont.setFontHeightInPoints((short) 10);
  430. headerFont.setBold(true);
  431. headerFont.setColor(IndexedColors.WHITE.getIndex());
  432. style.setFont(headerFont);
  433. styles.put("header", style);
  434. style = wb.createCellStyle();
  435. style.setAlignment(HorizontalAlignment.CENTER);
  436. style.setVerticalAlignment(VerticalAlignment.CENTER);
  437. Font totalFont = wb.createFont();
  438. totalFont.setFontName("Arial");
  439. totalFont.setFontHeightInPoints((short) 10);
  440. style.setFont(totalFont);
  441. styles.put("total", style);
  442. return styles;
  443. }
  444. /**
  445. * 创建单元格
  446. */
  447. public Cell createCell(Excel attr, Row row, int column)
  448. {
  449. // 创建列
  450. Cell cell = row.createCell(column);
  451. // 写入列信息
  452. cell.setCellValue(attr.name());
  453. setDataValidation(attr, row, column);
  454. cell.setCellStyle(styles.get("header"));
  455. return cell;
  456. }
  457. /**
  458. * 设置单元格信息
  459. *
  460. * @param value 单元格值
  461. * @param attr 注解相关
  462. * @param cell 单元格信息
  463. */
  464. public void setCellVo(Object value, Excel attr, Cell cell)
  465. {
  466. if (ColumnType.STRING == attr.cellType())
  467. {
  468. cell.setCellType(CellType.STRING);
  469. cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
  470. }
  471. else if (ColumnType.NUMERIC == attr.cellType())
  472. {
  473. cell.setCellType(CellType.NUMERIC);
  474. cell.setCellValue(Integer.parseInt(value + ""));
  475. }
  476. }
  477. /**
  478. * 创建表格样式
  479. */
  480. public void setDataValidation(Excel attr, Row row, int column)
  481. {
  482. if (attr.name().indexOf("注:") >= 0)
  483. {
  484. sheet.setColumnWidth(column, 6000);
  485. }
  486. else
  487. {
  488. // 设置列宽
  489. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  490. row.setHeight((short) (attr.height() * 20));
  491. }
  492. // 如果设置了提示信息则鼠标放上去提示.
  493. if (StringUtils.isNotEmpty(attr.prompt()))
  494. {
  495. // 这里默认设了2-101列提示.
  496. setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
  497. }
  498. // 如果设置了combo属性则本列只能选择不能输入
  499. if (attr.combo().length > 0)
  500. {
  501. // 这里默认设了2-101列只能选择不能输入.
  502. setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
  503. }
  504. }
  505. /**
  506. * 添加单元格
  507. */
  508. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  509. {
  510. Cell cell = null;
  511. try
  512. {
  513. // 设置行高
  514. row.setHeight((short) (attr.height() * 20));
  515. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  516. if (attr.isExport())
  517. {
  518. // 创建cell
  519. cell = row.createCell(column);
  520. cell.setCellStyle(styles.get("data"));
  521. // 用于读取对象中的属性
  522. Object value = getTargetValue(vo, field, attr);
  523. String dateFormat = attr.dateFormat();
  524. String readConverterExp = attr.readConverterExp();
  525. String separator = attr.separator();
  526. String dictType = attr.dictType();
  527. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  528. {
  529. cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
  530. }
  531. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  532. {
  533. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  534. }
  535. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  536. {
  537. cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
  538. }
  539. else if (value instanceof BigDecimal && -1 != attr.scale())
  540. {
  541. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
  542. }
  543. else
  544. {
  545. // 设置列类型
  546. setCellVo(value, attr, cell);
  547. }
  548. addStatisticsData(column, Convert.toStr(value), attr);
  549. }
  550. }
  551. catch (Exception e)
  552. {
  553. log.error("导出Excel失败{}", e);
  554. }
  555. return cell;
  556. }
  557. /**
  558. * 设置 POI XSSFSheet 单元格提示
  559. *
  560. * @param sheet 表单
  561. * @param promptTitle 提示标题
  562. * @param promptContent 提示内容
  563. * @param firstRow 开始行
  564. * @param endRow 结束行
  565. * @param firstCol 开始列
  566. * @param endCol 结束列
  567. */
  568. public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
  569. int firstCol, int endCol)
  570. {
  571. DataValidationHelper helper = sheet.getDataValidationHelper();
  572. DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
  573. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  574. DataValidation dataValidation = helper.createValidation(constraint, regions);
  575. dataValidation.createPromptBox(promptTitle, promptContent);
  576. dataValidation.setShowPromptBox(true);
  577. sheet.addValidationData(dataValidation);
  578. }
  579. /**
  580. * 设置某些列的值只能输入预制的数据,显示下拉框.
  581. *
  582. * @param sheet 要设置的sheet.
  583. * @param textlist 下拉框显示的内容
  584. * @param firstRow 开始行
  585. * @param endRow 结束行
  586. * @param firstCol 开始列
  587. * @param endCol 结束列
  588. * @return 设置好的sheet.
  589. */
  590. public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol)
  591. {
  592. DataValidationHelper helper = sheet.getDataValidationHelper();
  593. // 加载下拉列表内容
  594. DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
  595. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  596. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  597. // 数据有效性对象
  598. DataValidation dataValidation = helper.createValidation(constraint, regions);
  599. // 处理Excel兼容性问题
  600. if (dataValidation instanceof XSSFDataValidation)
  601. {
  602. dataValidation.setSuppressDropDownArrow(true);
  603. dataValidation.setShowErrorBox(true);
  604. }
  605. else
  606. {
  607. dataValidation.setSuppressDropDownArrow(false);
  608. }
  609. sheet.addValidationData(dataValidation);
  610. }
  611. /**
  612. * 解析导出值 0=男,1=女,2=未知
  613. *
  614. * @param propertyValue 参数值
  615. * @param converterExp 翻译注解
  616. * @param separator 分隔符
  617. * @return 解析后值
  618. */
  619. public static String convertByExp(String propertyValue, String converterExp, String separator)
  620. {
  621. StringBuilder propertyString = new StringBuilder();
  622. String[] convertSource = converterExp.split(",");
  623. for (String item : convertSource)
  624. {
  625. String[] itemArray = item.split("=");
  626. if (StringUtils.containsAny(separator, propertyValue))
  627. {
  628. for (String value : propertyValue.split(separator))
  629. {
  630. if (itemArray[0].equals(value))
  631. {
  632. propertyString.append(itemArray[1] + separator);
  633. break;
  634. }
  635. }
  636. }
  637. else
  638. {
  639. if (itemArray[0].equals(propertyValue))
  640. {
  641. return itemArray[1];
  642. }
  643. }
  644. }
  645. return StringUtils.stripEnd(propertyString.toString(), separator);
  646. }
  647. /**
  648. * 反向解析值 男=0,女=1,未知=2
  649. *
  650. * @param propertyValue 参数值
  651. * @param converterExp 翻译注解
  652. * @param separator 分隔符
  653. * @return 解析后值
  654. */
  655. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  656. {
  657. StringBuilder propertyString = new StringBuilder();
  658. String[] convertSource = converterExp.split(",");
  659. for (String item : convertSource)
  660. {
  661. String[] itemArray = item.split("=");
  662. if (StringUtils.containsAny(separator, propertyValue))
  663. {
  664. for (String value : propertyValue.split(separator))
  665. {
  666. if (itemArray[1].equals(value))
  667. {
  668. propertyString.append(itemArray[0] + separator);
  669. break;
  670. }
  671. }
  672. }
  673. else
  674. {
  675. if (itemArray[1].equals(propertyValue))
  676. {
  677. return itemArray[0];
  678. }
  679. }
  680. }
  681. return StringUtils.stripEnd(propertyString.toString(), separator);
  682. }
  683. /**
  684. * 解析字典值
  685. *
  686. * @param dictValue 字典值
  687. * @param dictType 字典类型
  688. * @param separator 分隔符
  689. * @return 字典标签
  690. */
  691. public static String convertDictByExp(String dictValue, String dictType, String separator)
  692. {
  693. return DictUtils.getDictLabel(dictType, dictValue, separator);
  694. }
  695. /**
  696. * 反向解析值字典值
  697. *
  698. * @param dictLabel 字典标签
  699. * @param dictType 字典类型
  700. * @param separator 分隔符
  701. * @return 字典值
  702. */
  703. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  704. {
  705. return DictUtils.getDictValue(dictType, dictLabel, separator);
  706. }
  707. /**
  708. * 合计统计信息
  709. */
  710. private void addStatisticsData(Integer index, String text, Excel entity)
  711. {
  712. if (entity != null && entity.isStatistics())
  713. {
  714. Double temp = 0D;
  715. if (!statistics.containsKey(index))
  716. {
  717. statistics.put(index, temp);
  718. }
  719. try
  720. {
  721. temp = Double.valueOf(text);
  722. }
  723. catch (NumberFormatException e)
  724. {
  725. }
  726. statistics.put(index, statistics.get(index) + temp);
  727. }
  728. }
  729. /**
  730. * 创建统计行
  731. */
  732. public void addStatisticsRow()
  733. {
  734. if (statistics.size() > 0)
  735. {
  736. Cell cell = null;
  737. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  738. Set<Integer> keys = statistics.keySet();
  739. cell = row.createCell(0);
  740. cell.setCellStyle(styles.get("total"));
  741. cell.setCellValue("合计");
  742. for (Integer key : keys)
  743. {
  744. cell = row.createCell(key);
  745. cell.setCellStyle(styles.get("total"));
  746. cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  747. }
  748. statistics.clear();
  749. }
  750. }
  751. /**
  752. * 编码文件名
  753. */
  754. public String encodingFilename(String filename)
  755. {
  756. filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
  757. return filename;
  758. }
  759. /**
  760. * 获取下载路径
  761. *
  762. * @param filename 文件名称
  763. */
  764. public String getAbsoluteFile(String filename)
  765. {
  766. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  767. File desc = new File(downloadPath);
  768. if (!desc.getParentFile().exists())
  769. {
  770. desc.getParentFile().mkdirs();
  771. }
  772. return downloadPath;
  773. }
  774. /**
  775. * 获取bean中的属性值
  776. *
  777. * @param vo 实体对象
  778. * @param field 字段
  779. * @param excel 注解
  780. * @return 最终的属性值
  781. * @throws Exception
  782. */
  783. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  784. {
  785. Object o = field.get(vo);
  786. if (StringUtils.isNotEmpty(excel.targetAttr()))
  787. {
  788. String target = excel.targetAttr();
  789. if (target.indexOf(".") > -1)
  790. {
  791. String[] targets = target.split("[.]");
  792. for (String name : targets)
  793. {
  794. o = getValue(o, name);
  795. }
  796. }
  797. else
  798. {
  799. o = getValue(o, target);
  800. }
  801. }
  802. return o;
  803. }
  804. /**
  805. * 以类的属性的get方法方法形式获取值
  806. *
  807. * @param o
  808. * @param name
  809. * @return value
  810. * @throws Exception
  811. */
  812. private Object getValue(Object o, String name) throws Exception
  813. {
  814. if (StringUtils.isNotEmpty(name))
  815. {
  816. Class<?> clazz = o.getClass();
  817. Field field = clazz.getDeclaredField(name);
  818. field.setAccessible(true);
  819. o = field.get(o);
  820. }
  821. return o;
  822. }
  823. /**
  824. * 得到所有定义字段
  825. */
  826. private void createExcelField()
  827. {
  828. this.fields = new ArrayList<Object[]>();
  829. List<Field> tempFields = new ArrayList<>();
  830. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  831. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  832. for (Field field : tempFields)
  833. {
  834. // 单注解
  835. if (field.isAnnotationPresent(Excel.class))
  836. {
  837. putToField(field, field.getAnnotation(Excel.class));
  838. }
  839. // 多注解
  840. if (field.isAnnotationPresent(Excels.class))
  841. {
  842. Excels attrs = field.getAnnotation(Excels.class);
  843. Excel[] excels = attrs.value();
  844. for (Excel excel : excels)
  845. {
  846. putToField(field, excel);
  847. }
  848. }
  849. }
  850. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  851. }
  852. /**
  853. * 放到字段集合中
  854. */
  855. private void putToField(Field field, Excel attr)
  856. {
  857. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  858. {
  859. this.fields.add(new Object[] { field, attr });
  860. }
  861. }
  862. /**
  863. * 创建一个工作簿
  864. */
  865. public void createWorkbook()
  866. {
  867. this.wb = new SXSSFWorkbook(500);
  868. }
  869. /**
  870. * 创建工作表
  871. *
  872. * @param sheetNo sheet数量
  873. * @param index 序号
  874. */
  875. public void createSheet(double sheetNo, int index)
  876. {
  877. this.sheet = wb.createSheet();
  878. this.styles = createStyles(wb);
  879. // 设置工作表的名称.
  880. if (sheetNo == 0)
  881. {
  882. wb.setSheetName(index, sheetName);
  883. }
  884. else
  885. {
  886. wb.setSheetName(index, sheetName + index);
  887. }
  888. }
  889. /**
  890. * 获取单元格值
  891. *
  892. * @param row 获取的行
  893. * @param column 获取单元格列号
  894. * @return 单元格值
  895. */
  896. public Object getCellValue(Row row, int column)
  897. {
  898. if (row == null)
  899. {
  900. return row;
  901. }
  902. Object val = "";
  903. try
  904. {
  905. Cell cell = row.getCell(column);
  906. if (StringUtils.isNotNull(cell))
  907. {
  908. if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA)
  909. {
  910. val = cell.getNumericCellValue();
  911. if (HSSFDateUtil.isCellDateFormatted(cell))
  912. {
  913. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  914. }
  915. else
  916. {
  917. if ((Double) val % 1 > 0)
  918. {
  919. val = new BigDecimal(val.toString());
  920. }
  921. else
  922. {
  923. val = new DecimalFormat("0").format(val);
  924. }
  925. }
  926. }
  927. else if (cell.getCellTypeEnum() == CellType.STRING)
  928. {
  929. val = cell.getStringCellValue();
  930. }
  931. else if (cell.getCellTypeEnum() == CellType.BOOLEAN)
  932. {
  933. val = cell.getBooleanCellValue();
  934. }
  935. else if (cell.getCellTypeEnum() == CellType.ERROR)
  936. {
  937. val = cell.getErrorCellValue();
  938. }
  939. }
  940. }
  941. catch (Exception e)
  942. {
  943. return val;
  944. }
  945. return val;
  946. }
  947. }