ExcelUtil.java 29 KB

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