ExcelUtil.java 36 KB

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