ExcelUtil.java 30 KB

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