ExcelUtil.java 35 KB

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