ExcelUtil.java 33 KB

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