ExcelUtil.java 33 KB

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