ExcelUtil.java 35 KB

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