ExcelUtil.java 33 KB

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