ExcelUtil.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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.Date;
  14. import java.util.HashMap;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.UUID;
  18. import org.apache.poi.hssf.usermodel.HSSFDateUtil;
  19. import org.apache.poi.ss.usermodel.BorderStyle;
  20. import org.apache.poi.ss.usermodel.Cell;
  21. import org.apache.poi.ss.usermodel.CellStyle;
  22. import org.apache.poi.ss.usermodel.CellType;
  23. import org.apache.poi.ss.usermodel.DataValidation;
  24. import org.apache.poi.ss.usermodel.DataValidationConstraint;
  25. import org.apache.poi.ss.usermodel.DataValidationHelper;
  26. import org.apache.poi.ss.usermodel.DateUtil;
  27. import org.apache.poi.ss.usermodel.FillPatternType;
  28. import org.apache.poi.ss.usermodel.Font;
  29. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  30. import org.apache.poi.ss.usermodel.IndexedColors;
  31. import org.apache.poi.ss.usermodel.Row;
  32. import org.apache.poi.ss.usermodel.Sheet;
  33. import org.apache.poi.ss.usermodel.VerticalAlignment;
  34. import org.apache.poi.ss.usermodel.Workbook;
  35. import org.apache.poi.ss.usermodel.WorkbookFactory;
  36. import org.apache.poi.ss.util.CellRangeAddressList;
  37. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  38. import org.apache.poi.xssf.usermodel.XSSFDataValidation;
  39. import org.slf4j.Logger;
  40. import org.slf4j.LoggerFactory;
  41. import com.ruoyi.common.annotation.Excel;
  42. import com.ruoyi.common.annotation.Excel.ColumnType;
  43. import com.ruoyi.common.annotation.Excel.Type;
  44. import com.ruoyi.common.annotation.Excels;
  45. import com.ruoyi.common.config.Global;
  46. import com.ruoyi.common.core.domain.AjaxResult;
  47. import com.ruoyi.common.core.text.Convert;
  48. import com.ruoyi.common.exception.BusinessException;
  49. import com.ruoyi.common.utils.DateUtils;
  50. import com.ruoyi.common.utils.StringUtils;
  51. import com.ruoyi.common.utils.reflect.ReflectUtils;
  52. /**
  53. * Excel相关处理
  54. *
  55. * @author ruoyi
  56. */
  57. public class ExcelUtil<T>
  58. {
  59. private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
  60. /**
  61. * Excel sheet最大行数,默认65536
  62. */
  63. public static final int sheetSize = 65536;
  64. /**
  65. * 工作表名称
  66. */
  67. private String sheetName;
  68. /**
  69. * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
  70. */
  71. private Type type;
  72. /**
  73. * 工作薄对象
  74. */
  75. private Workbook wb;
  76. /**
  77. * 工作表对象
  78. */
  79. private Sheet sheet;
  80. /**
  81. * 样式列表
  82. */
  83. private Map<String, CellStyle> styles;
  84. /**
  85. * 导入导出数据列表
  86. */
  87. private List<T> list;
  88. /**
  89. * 注解列表
  90. */
  91. private List<Object[]> fields;
  92. /**
  93. * 实体对象
  94. */
  95. public Class<T> clazz;
  96. public ExcelUtil(Class<T> clazz)
  97. {
  98. this.clazz = clazz;
  99. }
  100. public void init(List<T> list, String sheetName, Type type)
  101. {
  102. if (list == null)
  103. {
  104. list = new ArrayList<T>();
  105. }
  106. this.list = list;
  107. this.sheetName = sheetName;
  108. this.type = type;
  109. createExcelField();
  110. createWorkbook();
  111. }
  112. /**
  113. * 对excel表单默认第一个索引名转换成list
  114. *
  115. * @param is 输入流
  116. * @return 转换后集合
  117. */
  118. public List<T> importExcel(InputStream is) throws Exception
  119. {
  120. return importExcel(StringUtils.EMPTY, is);
  121. }
  122. /**
  123. * 对excel表单指定表格索引名转换成list
  124. *
  125. * @param sheetName 表格索引名
  126. * @param is 输入流
  127. * @return 转换后集合
  128. */
  129. public List<T> importExcel(String sheetName, InputStream is) throws Exception
  130. {
  131. this.type = Type.IMPORT;
  132. this.wb = WorkbookFactory.create(is);
  133. List<T> list = new ArrayList<T>();
  134. Sheet sheet = null;
  135. if (StringUtils.isNotEmpty(sheetName))
  136. {
  137. // 如果指定sheet名,则取指定sheet中的内容.
  138. sheet = wb.getSheet(sheetName);
  139. }
  140. else
  141. {
  142. // 如果传入的sheet名不存在则默认指向第1个sheet.
  143. sheet = wb.getSheetAt(0);
  144. }
  145. if (sheet == null)
  146. {
  147. throw new IOException("文件sheet不存在");
  148. }
  149. int rows = sheet.getPhysicalNumberOfRows();
  150. if (rows > 0)
  151. {
  152. // 定义一个map用于存放excel列的序号和field.
  153. Map<String, Integer> cellMap = new HashMap<String, Integer>();
  154. // 获取表头
  155. Row heard = sheet.getRow(0);
  156. for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
  157. {
  158. Cell cell = heard.getCell(i);
  159. if (StringUtils.isNotNull(cell))
  160. {
  161. String value = this.getCellValue(heard, i).toString();
  162. cellMap.put(value, i);
  163. }
  164. else
  165. {
  166. cellMap.put(null, i);
  167. }
  168. }
  169. // 有数据时才处理 得到类的所有field.
  170. Field[] allFields = clazz.getDeclaredFields();
  171. // 定义一个map用于存放列的序号和field.
  172. Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
  173. for (int col = 0; col < allFields.length; col++)
  174. {
  175. Field field = allFields[col];
  176. Excel attr = field.getAnnotation(Excel.class);
  177. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  178. {
  179. // 设置类的私有字段属性可访问.
  180. field.setAccessible(true);
  181. Integer column = cellMap.get(attr.name());
  182. fieldsMap.put(column, field);
  183. }
  184. }
  185. for (int i = 1; i < rows; i++)
  186. {
  187. // 从第2行开始取数据,默认第一行是表头.
  188. Row row = sheet.getRow(i);
  189. T entity = null;
  190. for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet())
  191. {
  192. Object val = this.getCellValue(row, entry.getKey());
  193. // 如果不存在实例则新建.
  194. entity = (entity == null ? clazz.newInstance() : entity);
  195. // 从map中得到对应列的field.
  196. Field field = fieldsMap.get(entry.getKey());
  197. // 取得类型,并根据对象类型设置值.
  198. Class<?> fieldType = field.getType();
  199. if (String.class == fieldType)
  200. {
  201. String s = Convert.toStr(val);
  202. if (StringUtils.endsWith(s, ".0"))
  203. {
  204. val = StringUtils.substringBefore(s, ".0");
  205. }
  206. else
  207. {
  208. String dateFormat = field.getAnnotation(Excel.class).dateFormat();
  209. if (StringUtils.isNotEmpty(dateFormat))
  210. {
  211. val = DateUtils.parseDateToStr(dateFormat, (Date) val);
  212. }
  213. else
  214. {
  215. val = Convert.toStr(val);
  216. }
  217. }
  218. }
  219. else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType))
  220. {
  221. val = Convert.toInt(val);
  222. }
  223. else if ((Long.TYPE == fieldType) || (Long.class == fieldType))
  224. {
  225. val = Convert.toLong(val);
  226. }
  227. else if ((Double.TYPE == fieldType) || (Double.class == fieldType))
  228. {
  229. val = Convert.toDouble(val);
  230. }
  231. else if ((Float.TYPE == fieldType) || (Float.class == fieldType))
  232. {
  233. val = Convert.toFloat(val);
  234. }
  235. else if (BigDecimal.class == fieldType)
  236. {
  237. val = Convert.toBigDecimal(val);
  238. }
  239. else if (Date.class == fieldType)
  240. {
  241. if (val instanceof String)
  242. {
  243. val = DateUtils.parseDate(val);
  244. }
  245. else if (val instanceof Double)
  246. {
  247. val = DateUtil.getJavaDate((Double) val);
  248. }
  249. }
  250. if (StringUtils.isNotNull(fieldType))
  251. {
  252. Excel attr = field.getAnnotation(Excel.class);
  253. String propertyName = field.getName();
  254. if (StringUtils.isNotEmpty(attr.targetAttr()))
  255. {
  256. propertyName = field.getName() + "." + attr.targetAttr();
  257. }
  258. else if (StringUtils.isNotEmpty(attr.readConverterExp()))
  259. {
  260. val = reverseByExp(String.valueOf(val), attr.readConverterExp(), 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 BusinessException("导出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. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  508. {
  509. cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
  510. }
  511. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  512. {
  513. cell.setCellValue(convertByExp(String.valueOf(value), readConverterExp, separator));
  514. }
  515. else
  516. {
  517. // 设置列类型
  518. setCellVo(value, attr, cell);
  519. }
  520. }
  521. }
  522. catch (Exception e)
  523. {
  524. log.error("导出Excel失败{}", e);
  525. }
  526. return cell;
  527. }
  528. /**
  529. * 设置 POI XSSFSheet 单元格提示
  530. *
  531. * @param sheet 表单
  532. * @param promptTitle 提示标题
  533. * @param promptContent 提示内容
  534. * @param firstRow 开始行
  535. * @param endRow 结束行
  536. * @param firstCol 开始列
  537. * @param endCol 结束列
  538. */
  539. public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
  540. int firstCol, int endCol)
  541. {
  542. DataValidationHelper helper = sheet.getDataValidationHelper();
  543. DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
  544. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  545. DataValidation dataValidation = helper.createValidation(constraint, regions);
  546. dataValidation.createPromptBox(promptTitle, promptContent);
  547. dataValidation.setShowPromptBox(true);
  548. sheet.addValidationData(dataValidation);
  549. }
  550. /**
  551. * 设置某些列的值只能输入预制的数据,显示下拉框.
  552. *
  553. * @param sheet 要设置的sheet.
  554. * @param textlist 下拉框显示的内容
  555. * @param firstRow 开始行
  556. * @param endRow 结束行
  557. * @param firstCol 开始列
  558. * @param endCol 结束列
  559. * @return 设置好的sheet.
  560. */
  561. public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol)
  562. {
  563. DataValidationHelper helper = sheet.getDataValidationHelper();
  564. // 加载下拉列表内容
  565. DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
  566. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  567. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  568. // 数据有效性对象
  569. DataValidation dataValidation = helper.createValidation(constraint, regions);
  570. // 处理Excel兼容性问题
  571. if (dataValidation instanceof XSSFDataValidation)
  572. {
  573. dataValidation.setSuppressDropDownArrow(true);
  574. dataValidation.setShowErrorBox(true);
  575. }
  576. else
  577. {
  578. dataValidation.setSuppressDropDownArrow(false);
  579. }
  580. sheet.addValidationData(dataValidation);
  581. }
  582. /**
  583. * 解析导出值 0=男,1=女,2=未知
  584. *
  585. * @param propertyValue 参数值
  586. * @param converterExp 翻译注解
  587. * @param separator 分隔符
  588. * @return 解析后值
  589. * @throws Exception
  590. */
  591. public static String convertByExp(String propertyValue, String converterExp, String separator) throws Exception
  592. {
  593. StringBuilder propertyString = new StringBuilder();
  594. try
  595. {
  596. String[] convertSource = converterExp.split(",");
  597. for (String item : convertSource)
  598. {
  599. String[] itemArray = item.split("=");
  600. if (StringUtils.containsAny(separator, propertyValue))
  601. {
  602. for (String value : propertyValue.split(separator))
  603. {
  604. if (itemArray[0].equals(value))
  605. {
  606. propertyString.append(itemArray[1] + separator);
  607. break;
  608. }
  609. }
  610. }
  611. else
  612. {
  613. if (itemArray[0].equals(propertyValue))
  614. {
  615. return itemArray[1];
  616. }
  617. }
  618. }
  619. }
  620. catch (Exception e)
  621. {
  622. throw e;
  623. }
  624. return StringUtils.stripEnd(propertyString.toString(), separator);
  625. }
  626. /**
  627. * 反向解析值 男=0,女=1,未知=2
  628. *
  629. * @param propertyValue 参数值
  630. * @param converterExp 翻译注解
  631. * @param separator 分隔符
  632. * @return 解析后值
  633. * @throws Exception
  634. */
  635. public static String reverseByExp(String propertyValue, String converterExp, String separator) throws Exception
  636. {
  637. StringBuilder propertyString = new StringBuilder();
  638. try
  639. {
  640. String[] convertSource = converterExp.split(",");
  641. for (String item : convertSource)
  642. {
  643. String[] itemArray = item.split("=");
  644. if (StringUtils.containsAny(separator, propertyValue))
  645. {
  646. for (String value : propertyValue.split(separator))
  647. {
  648. if (itemArray[1].equals(value))
  649. {
  650. propertyString.append(itemArray[0] + separator);
  651. break;
  652. }
  653. }
  654. }
  655. else
  656. {
  657. if (itemArray[1].equals(propertyValue))
  658. {
  659. return itemArray[0];
  660. }
  661. }
  662. }
  663. }
  664. catch (Exception e)
  665. {
  666. throw e;
  667. }
  668. return StringUtils.stripEnd(propertyString.toString(), separator);
  669. }
  670. /**
  671. * 编码文件名
  672. */
  673. public String encodingFilename(String filename)
  674. {
  675. filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
  676. return filename;
  677. }
  678. /**
  679. * 获取下载路径
  680. *
  681. * @param filename 文件名称
  682. */
  683. public String getAbsoluteFile(String filename)
  684. {
  685. String downloadPath = Global.getDownloadPath() + filename;
  686. File desc = new File(downloadPath);
  687. if (!desc.getParentFile().exists())
  688. {
  689. desc.getParentFile().mkdirs();
  690. }
  691. return downloadPath;
  692. }
  693. /**
  694. * 获取bean中的属性值
  695. *
  696. * @param vo 实体对象
  697. * @param field 字段
  698. * @param excel 注解
  699. * @return 最终的属性值
  700. * @throws Exception
  701. */
  702. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  703. {
  704. Object o = field.get(vo);
  705. if (StringUtils.isNotEmpty(excel.targetAttr()))
  706. {
  707. String target = excel.targetAttr();
  708. if (target.indexOf(".") > -1)
  709. {
  710. String[] targets = target.split("[.]");
  711. for (String name : targets)
  712. {
  713. o = getValue(o, name);
  714. }
  715. }
  716. else
  717. {
  718. o = getValue(o, target);
  719. }
  720. }
  721. return o;
  722. }
  723. /**
  724. * 以类的属性的get方法方法形式获取值
  725. *
  726. * @param o
  727. * @param name
  728. * @return value
  729. * @throws Exception
  730. */
  731. private Object getValue(Object o, String name) throws Exception
  732. {
  733. if (StringUtils.isNotEmpty(name))
  734. {
  735. Class<?> clazz = o.getClass();
  736. String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
  737. Method method = clazz.getMethod(methodName);
  738. o = method.invoke(o);
  739. }
  740. return o;
  741. }
  742. /**
  743. * 得到所有定义字段
  744. */
  745. private void createExcelField()
  746. {
  747. this.fields = new ArrayList<Object[]>();
  748. List<Field> tempFields = new ArrayList<>();
  749. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  750. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  751. for (Field field : tempFields)
  752. {
  753. // 单注解
  754. if (field.isAnnotationPresent(Excel.class))
  755. {
  756. putToField(field, field.getAnnotation(Excel.class));
  757. }
  758. // 多注解
  759. if (field.isAnnotationPresent(Excels.class))
  760. {
  761. Excels attrs = field.getAnnotation(Excels.class);
  762. Excel[] excels = attrs.value();
  763. for (Excel excel : excels)
  764. {
  765. putToField(field, excel);
  766. }
  767. }
  768. }
  769. }
  770. /**
  771. * 放到字段集合中
  772. */
  773. private void putToField(Field field, Excel attr)
  774. {
  775. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  776. {
  777. this.fields.add(new Object[] { field, attr });
  778. }
  779. }
  780. /**
  781. * 创建一个工作簿
  782. */
  783. public void createWorkbook()
  784. {
  785. this.wb = new SXSSFWorkbook(500);
  786. }
  787. /**
  788. * 创建工作表
  789. *
  790. * @param sheetNo sheet数量
  791. * @param index 序号
  792. */
  793. public void createSheet(double sheetNo, int index)
  794. {
  795. this.sheet = wb.createSheet();
  796. this.styles = createStyles(wb);
  797. // 设置工作表的名称.
  798. if (sheetNo == 0)
  799. {
  800. wb.setSheetName(index, sheetName);
  801. }
  802. else
  803. {
  804. wb.setSheetName(index, sheetName + index);
  805. }
  806. }
  807. /**
  808. * 获取单元格值
  809. *
  810. * @param row 获取的行
  811. * @param column 获取单元格列号
  812. * @return 单元格值
  813. */
  814. public Object getCellValue(Row row, int column)
  815. {
  816. if (row == null)
  817. {
  818. return row;
  819. }
  820. Object val = "";
  821. try
  822. {
  823. Cell cell = row.getCell(column);
  824. if (StringUtils.isNotNull(cell))
  825. {
  826. if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA)
  827. {
  828. val = cell.getNumericCellValue();
  829. if (HSSFDateUtil.isCellDateFormatted(cell))
  830. {
  831. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  832. }
  833. else
  834. {
  835. if ((Double) val % 1 > 0)
  836. {
  837. val = new DecimalFormat("0.00").format(val);
  838. }
  839. else
  840. {
  841. val = new DecimalFormat("0").format(val);
  842. }
  843. }
  844. }
  845. else if (cell.getCellTypeEnum() == CellType.STRING)
  846. {
  847. val = cell.getStringCellValue();
  848. }
  849. else if (cell.getCellTypeEnum() == CellType.BOOLEAN)
  850. {
  851. val = cell.getBooleanCellValue();
  852. }
  853. else if (cell.getCellTypeEnum() == CellType.ERROR)
  854. {
  855. val = cell.getErrorCellValue();
  856. }
  857. }
  858. }
  859. catch (Exception e)
  860. {
  861. return val;
  862. }
  863. return val;
  864. }
  865. }