ExcelUtil.java 36 KB

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