ExcelUtil.java 33 KB

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