ExcelUtil.java 32 KB

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