ExcelUtil.java 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  1. package com.ruoyi.common.utils.poi;
  2. import com.ruoyi.common.annotation.Excel;
  3. import com.ruoyi.common.annotation.Excel.ColumnType;
  4. import com.ruoyi.common.annotation.Excel.Type;
  5. import com.ruoyi.common.annotation.Excels;
  6. import com.ruoyi.common.config.RuoYiConfig;
  7. import com.ruoyi.common.core.domain.AjaxResult;
  8. import com.ruoyi.common.core.text.Convert;
  9. import com.ruoyi.common.exception.CustomException;
  10. import com.ruoyi.common.utils.DateUtils;
  11. import com.ruoyi.common.utils.DictUtils;
  12. import com.ruoyi.common.utils.StringUtils;
  13. import com.ruoyi.common.utils.reflect.ReflectUtils;
  14. import org.apache.poi.ss.usermodel.*;
  15. import org.apache.poi.ss.util.CellRangeAddressList;
  16. import org.apache.poi.ss.util.CellReference;
  17. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  18. import org.apache.poi.xssf.usermodel.XSSFDataValidation;
  19. import org.slf4j.Logger;
  20. import org.slf4j.LoggerFactory;
  21. import java.io.*;
  22. import java.lang.reflect.Field;
  23. import java.math.BigDecimal;
  24. import java.text.DecimalFormat;
  25. import java.util.*;
  26. import java.util.stream.Collectors;
  27. /**
  28. * Excel相关处理
  29. *
  30. * @author ruoyi
  31. */
  32. public class ExcelUtil<T>
  33. {
  34. private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
  35. /**
  36. * Excel sheet最大行数,默认65536
  37. */
  38. public static final int sheetSize = 65536;
  39. /**
  40. * 工作表名称
  41. */
  42. private String sheetName;
  43. /**
  44. * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
  45. */
  46. private Type type;
  47. /**
  48. * 工作薄对象
  49. */
  50. private Workbook wb;
  51. /**
  52. * 工作表对象
  53. */
  54. private Sheet sheet;
  55. /**
  56. * 样式列表
  57. */
  58. private Map<String, CellStyle> styles;
  59. /**
  60. * 导入导出数据列表
  61. */
  62. private List<T> list;
  63. /**
  64. * 注解列表
  65. */
  66. private List<Object[]> fields;
  67. /**
  68. * 统计列表
  69. */
  70. private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
  71. /**
  72. * 数字格式
  73. */
  74. private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
  75. /**
  76. * 实体对象
  77. */
  78. public Class<T> clazz;
  79. public ExcelUtil(Class<T> clazz)
  80. {
  81. this.clazz = clazz;
  82. }
  83. public void init(List<T> list, String sheetName, Type type)
  84. {
  85. if (list == null)
  86. {
  87. list = new ArrayList<T>();
  88. }
  89. this.list = list;
  90. this.sheetName = sheetName;
  91. this.type = type;
  92. createExcelField();
  93. createWorkbook();
  94. }
  95. /**
  96. * 对excel表单默认第一个索引名转换成list
  97. *
  98. * @param is 输入流
  99. * @return 转换后集合
  100. */
  101. public List<T> importExcel(InputStream is) throws Exception
  102. {
  103. return importExcel(StringUtils.EMPTY, is);
  104. }
  105. /**
  106. * 对excel表单指定表格索引名转换成list
  107. *
  108. * @param sheetName 表格索引名
  109. * @param is 输入流
  110. * @return 转换后集合
  111. */
  112. public List<T> importExcel(String sheetName, InputStream is) throws Exception
  113. {
  114. this.type = Type.IMPORT;
  115. this.wb = WorkbookFactory.create(is);
  116. List<T> list = new ArrayList<T>();
  117. Sheet sheet = null;
  118. if (StringUtils.isNotEmpty(sheetName))
  119. {
  120. // 如果指定sheet名,则取指定sheet中的内容.
  121. sheet = wb.getSheet(sheetName);
  122. }
  123. else
  124. {
  125. // 如果传入的sheet名不存在则默认指向第1个sheet.
  126. sheet = wb.getSheetAt(0);
  127. }
  128. if (sheet == null)
  129. {
  130. throw new IOException("文件sheet不存在");
  131. }
  132. int rows = sheet.getPhysicalNumberOfRows();
  133. if (rows > 0)
  134. {
  135. // 定义一个map用于存放excel列的序号和field.
  136. Map<String, Integer> cellMap = new HashMap<String, Integer>();
  137. // 获取表头
  138. Row heard = sheet.getRow(0);
  139. for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
  140. {
  141. Cell cell = heard.getCell(i);
  142. if (StringUtils.isNotNull(cell))
  143. {
  144. String value = this.getCellValue(heard, i).toString();
  145. cellMap.put(value, i);
  146. }
  147. else
  148. {
  149. cellMap.put(null, i);
  150. }
  151. }
  152. // 有数据时才处理 得到类的所有field.
  153. Field[] allFields = clazz.getDeclaredFields();
  154. // 定义一个map用于存放列的序号和field.
  155. Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
  156. for (int col = 0; col < allFields.length; col++)
  157. {
  158. Field field = allFields[col];
  159. Excel attr = field.getAnnotation(Excel.class);
  160. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  161. {
  162. // 设置类的私有字段属性可访问.
  163. field.setAccessible(true);
  164. Integer column = cellMap.get(attr.name());
  165. if (column != null)
  166. {
  167. fieldsMap.put(column, field);
  168. }
  169. }
  170. }
  171. for (int i = 1; i < rows; i++)
  172. {
  173. // 从第2行开始取数据,默认第一行是表头.
  174. Row row = sheet.getRow(i);
  175. T entity = null;
  176. for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet())
  177. {
  178. Object val = this.getCellValue(row, entry.getKey());
  179. // 如果不存在实例则新建.
  180. entity = (entity == null ? clazz.newInstance() : entity);
  181. // 从map中得到对应列的field.
  182. Field field = fieldsMap.get(entry.getKey());
  183. // 取得类型,并根据对象类型设置值.
  184. Class<?> fieldType = field.getType();
  185. if (String.class == fieldType)
  186. {
  187. String s = Convert.toStr(val);
  188. if (StringUtils.endsWith(s, ".0"))
  189. {
  190. val = StringUtils.substringBefore(s, ".0");
  191. }
  192. else
  193. {
  194. val = Convert.toStr(val);
  195. }
  196. }
  197. else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
  198. {
  199. val = Convert.toInt(val);
  200. }
  201. else if (Long.TYPE == fieldType || Long.class == fieldType)
  202. {
  203. val = Convert.toLong(val);
  204. }
  205. else if (Double.TYPE == fieldType || Double.class == fieldType)
  206. {
  207. val = Convert.toDouble(val);
  208. }
  209. else if (Float.TYPE == fieldType || Float.class == fieldType)
  210. {
  211. val = Convert.toFloat(val);
  212. }
  213. else if (BigDecimal.class == fieldType)
  214. {
  215. val = Convert.toBigDecimal(val);
  216. }
  217. else if (Date.class == fieldType)
  218. {
  219. if (val instanceof String)
  220. {
  221. val = DateUtils.parseDate(val);
  222. }
  223. else if (val instanceof Double)
  224. {
  225. val = DateUtil.getJavaDate((Double) val);
  226. }
  227. }
  228. else if (Boolean.TYPE == fieldType || Boolean.class == fieldType)
  229. {
  230. val = Convert.toBool(val, false);
  231. }
  232. if (StringUtils.isNotNull(fieldType))
  233. {
  234. Excel attr = field.getAnnotation(Excel.class);
  235. String propertyName = field.getName();
  236. if (StringUtils.isNotEmpty(attr.targetAttr()))
  237. {
  238. propertyName = field.getName() + "." + attr.targetAttr();
  239. }
  240. else if (StringUtils.isNotEmpty(attr.readConverterExp()))
  241. {
  242. val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
  243. }
  244. else if (StringUtils.isNotEmpty(attr.dictType()))
  245. {
  246. val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
  247. }
  248. ReflectUtils.invokeSetter(entity, propertyName, val);
  249. }
  250. }
  251. list.add(entity);
  252. }
  253. }
  254. return list;
  255. }
  256. /**
  257. * 对list数据源将其里面的数据导入到excel表单
  258. *
  259. * @param list 导出数据集合
  260. * @param sheetName 工作表的名称
  261. * @return 结果
  262. */
  263. public AjaxResult feesExportExcel(List<T> list, String sheetName, List<String> fees)
  264. {
  265. this.init(list, sheetName, Type.EXPORT);
  266. return feesExportExcel(fees);
  267. }
  268. /**
  269. * 对list数据源将其里面的数据导入到excel表单
  270. *
  271. * @return 结果
  272. */
  273. public AjaxResult feesExportExcel(List<String> fees)
  274. {
  275. OutputStream out = null;
  276. try
  277. {
  278. // 取出一共有多少个sheet.
  279. double sheetNo = Math.ceil(list.size() / sheetSize);
  280. for (int index = 0; index <= sheetNo; index++)
  281. {
  282. createSheet(sheetNo, index);
  283. // 产生一行
  284. Row row = sheet.createRow(0);
  285. int column = 0;
  286. // 写入各个字段的列头名称
  287. for (Object[] os : fields)
  288. {
  289. Excel excel = (Excel) os[1];
  290. this.createCell(excel, row, column++);
  291. }
  292. if (Type.EXPORT.equals(type))
  293. {
  294. fillExcelData(index, row);
  295. addStatisticsRow();
  296. }
  297. }
  298. Row row = sheet.createRow(list.size() + 1);
  299. row.createCell(1).setCellValue("全部累计");
  300. if (StringUtils.isNotEmpty(fees)) {
  301. if (StringUtils.isNotNull(fees.get(0))) {
  302. row.createCell(3).setCellValue(fees.get(0));
  303. }
  304. if (StringUtils.isNotNull(fees.get(1))) {
  305. row.createCell(4).setCellValue(fees.get(1));
  306. }
  307. if (StringUtils.isNotNull(fees.get(2))) {
  308. row.createCell(5).setCellValue(fees.get(2));
  309. }
  310. }
  311. String filename = encodingFilename(sheetName);
  312. out = new FileOutputStream(getAbsoluteFile(filename));
  313. wb.write(out);
  314. return AjaxResult.success(filename);
  315. }
  316. catch (Exception e)
  317. {
  318. log.error("导出Excel异常{}", e.getMessage());
  319. throw new CustomException("导出Excel失败,请联系网站管理员!");
  320. }
  321. finally
  322. {
  323. if (wb != null)
  324. {
  325. try
  326. {
  327. wb.close();
  328. }
  329. catch (IOException e1)
  330. {
  331. e1.printStackTrace();
  332. }
  333. }
  334. if (out != null)
  335. {
  336. try
  337. {
  338. out.close();
  339. }
  340. catch (IOException e1)
  341. {
  342. e1.printStackTrace();
  343. }
  344. }
  345. }
  346. }
  347. /**
  348. * 对list数据源将其里面的数据导入到excel表单
  349. *
  350. * @param list 导出数据集合
  351. * @param sheetName 工作表的名称
  352. * @return 结果
  353. */
  354. public AjaxResult exportExcel(List<T> list, String sheetName)
  355. {
  356. this.init(list, sheetName, Type.EXPORT);
  357. return exportExcel();
  358. }
  359. /**
  360. * 总账统计导入到excel表单
  361. *
  362. * @param list 导出数据集合
  363. * @param sheetName 工作表的名称
  364. * @return 结果
  365. */
  366. public AjaxResult statisticsExportExcel(List<T> list, String sheetName)
  367. {
  368. this.init(list, sheetName, Type.EXPORT);
  369. return statisticsExportExcel();
  370. }
  371. /**
  372. * 单票分析导入到excel表单
  373. *
  374. * @param list 导出数据集合
  375. * @param sheetName 工作表的名称
  376. * @return 结果
  377. */
  378. public AjaxResult singleAnalysisExportExcel(List<T> list, Map<String, Object> map, String sheetName)
  379. {
  380. this.init(list, sheetName, Type.EXPORT);
  381. return singleAnalysisExportExcel(map);
  382. }
  383. /**
  384. * 单票分析费用导入到excel表单
  385. *
  386. * @param list 导出数据集合
  387. * @param sheetName 工作表的名称
  388. * @return 结果
  389. */
  390. public AjaxResult singleAnalysisFeesExportExcel(List<T> list, String sheetName)
  391. {
  392. this.init(list, sheetName, Type.EXPORT);
  393. return singleAnalysisFeesExportExcel();
  394. }
  395. /**
  396. * 对list数据源将其里面的数据导入到excel表单
  397. *
  398. * @param sheetName 工作表的名称
  399. * @return 结果
  400. */
  401. public AjaxResult importTemplateExcel(String sheetName)
  402. {
  403. this.init(null, sheetName, Type.IMPORT);
  404. return exportExcel();
  405. }
  406. /**
  407. * 对list数据源将其里面的数据导入到excel表单
  408. *
  409. * @return 结果
  410. */
  411. public AjaxResult exportExcel()
  412. {
  413. OutputStream out = null;
  414. try
  415. {
  416. // 取出一共有多少个sheet.
  417. double sheetNo = Math.ceil(list.size() / sheetSize);
  418. for (int index = 0; index <= sheetNo; index++)
  419. {
  420. createSheet(sheetNo, index);
  421. // 产生一行
  422. Row row = sheet.createRow(0);
  423. int column = 0;
  424. // 写入各个字段的列头名称
  425. for (Object[] os : fields)
  426. {
  427. Excel excel = (Excel) os[1];
  428. this.createCell(excel, row, column++);
  429. }
  430. if (Type.EXPORT.equals(type))
  431. {
  432. fillExcelData(index, row);
  433. addStatisticsRow();
  434. }
  435. }
  436. String filename = encodingFilename(sheetName);
  437. out = new FileOutputStream(getAbsoluteFile(filename));
  438. wb.write(out);
  439. return AjaxResult.success(filename);
  440. }
  441. catch (Exception e)
  442. {
  443. log.error("导出Excel异常{}", e.getMessage());
  444. throw new CustomException("导出Excel失败,请联系网站管理员!");
  445. }
  446. finally
  447. {
  448. if (wb != null)
  449. {
  450. try
  451. {
  452. wb.close();
  453. }
  454. catch (IOException e1)
  455. {
  456. e1.printStackTrace();
  457. }
  458. }
  459. if (out != null)
  460. {
  461. try
  462. {
  463. out.close();
  464. }
  465. catch (IOException e1)
  466. {
  467. e1.printStackTrace();
  468. }
  469. }
  470. }
  471. }
  472. /**
  473. * 总账统计导入到excel表单
  474. *
  475. * @return 结果
  476. */
  477. public AjaxResult statisticsExportExcel()
  478. {
  479. OutputStream out = null;
  480. try
  481. {
  482. // 取出一共有多少个sheet.
  483. double sheetNo = Math.ceil(list.size() / sheetSize);
  484. for (int index = 0; index <= sheetNo; index++)
  485. {
  486. createSheet(sheetNo, index);
  487. // 产生一行
  488. Row row = sheet.createRow(0);
  489. int column = 0;
  490. // 写入各个字段的列头名称
  491. for (Object[] os : fields)
  492. {
  493. Excel excel = (Excel) os[1];
  494. this.createCell(excel, row, column++);
  495. }
  496. if (Type.EXPORT.equals(type))
  497. {
  498. fillExcelData(index, row);
  499. addStatisticsRow();
  500. }
  501. }
  502. Row row = sheet.createRow(list.size() + 1);
  503. row.createCell(1).setCellValue("全部累计");
  504. row.createCell(3).setCellValue("仓储费");
  505. row.createCell(4).setCellValue("出入库费用");
  506. row.createCell(5).setCellValue("合计人民币");
  507. String filename = encodingFilename(sheetName);
  508. out = new FileOutputStream(getAbsoluteFile(filename));
  509. wb.write(out);
  510. return AjaxResult.success(filename);
  511. }
  512. catch (Exception e)
  513. {
  514. log.error("导出Excel异常{}", e.getMessage());
  515. throw new CustomException("导出Excel失败,请联系网站管理员!");
  516. }
  517. finally
  518. {
  519. if (wb != null)
  520. {
  521. try
  522. {
  523. wb.close();
  524. }
  525. catch (IOException e1)
  526. {
  527. e1.printStackTrace();
  528. }
  529. }
  530. if (out != null)
  531. {
  532. try
  533. {
  534. out.close();
  535. }
  536. catch (IOException e1)
  537. {
  538. e1.printStackTrace();
  539. }
  540. }
  541. }
  542. }
  543. /**
  544. * 单票分析导入到excel表单
  545. *
  546. * @return 结果
  547. */
  548. public AjaxResult singleAnalysisExportExcel(Map<String, Object> map)
  549. {
  550. OutputStream out = null;
  551. try
  552. {
  553. // 取出一共有多少个sheet.
  554. double sheetNo = Math.ceil(list.size() / sheetSize);
  555. for (int index = 0; index <= sheetNo; index++)
  556. {
  557. createSheet(sheetNo, index);
  558. // 产生一行
  559. Row row = sheet.createRow(0);
  560. int column = 0;
  561. // 写入各个字段的列头名称
  562. for (Object[] os : fields)
  563. {
  564. Excel excel = (Excel) os[1];
  565. this.createCell(excel, row, column++);
  566. }
  567. if (Type.EXPORT.equals(type))
  568. {
  569. fillExcelData(index, row);
  570. addStatisticsRow();
  571. }
  572. }
  573. Row row = sheet.createRow(list.size() + 1);
  574. Cell cell;// 单元格
  575. String colString;//长度转成ABC后的列
  576. String sumString;//求和公式
  577. Integer[] line = {3, 4, 6, 7, 8, 9};
  578. cell = row.createCell(0);// 创建单元格
  579. cell.setCellValue("合计:");
  580. int totalRows = sheet.getPhysicalNumberOfRows();
  581. for (Integer l : line) {
  582. cell = row.createCell(l);// 创建单元格
  583. cell.setCellStyle(styles.get("total"));// 设置单元格样式
  584. colString = CellReference.convertNumToColString(l); //长度转成ABC列
  585. //求和公式 求i9至i12单元格的总和
  586. if (l == 4 || l == 7) {
  587. sumString = "SUM(" + colString + "2:" + colString + (totalRows-1) + ") / 1000";
  588. } else {
  589. sumString = "SUM(" + colString + "2:" + colString + (totalRows-1) + ")";
  590. }
  591. cell.setCellFormula(sumString);// 把公式塞入合计列
  592. }
  593. wb.setForceFormulaRecalculation(true);
  594. String mblno = "", corpName = "", goodsName = "";
  595. if (map.containsKey("mblno")) {
  596. mblno = map.get("mblno").toString();
  597. }
  598. if (map.containsKey("corpName")) {
  599. corpName = map.get("corpName").toString();
  600. }
  601. if (map.containsKey("goodsName")) {
  602. goodsName = map.get("goodsName").toString();
  603. }
  604. Row primaryRow = sheet.createRow(list.size() + 2);
  605. primaryRow.createCell(1).setCellValue("货主:");
  606. cell = primaryRow.createCell(2);// 创建单元格
  607. cell.setCellValue(corpName);
  608. primaryRow.createCell(3).setCellValue("提单号:");
  609. cell = primaryRow.createCell(4);// 创建单元格
  610. cell.setCellValue(mblno);
  611. primaryRow.createCell(5).setCellValue("品名:");
  612. cell = primaryRow.createCell(6);// 创建单元格
  613. cell.setCellValue(goodsName);
  614. String filename = encodingFilename(sheetName);
  615. out = new FileOutputStream(getAbsoluteFile(filename));
  616. wb.write(out);
  617. return AjaxResult.success(filename);
  618. }
  619. catch (Exception e)
  620. {
  621. log.error("导出Excel异常{}", e.getMessage());
  622. throw new CustomException("导出Excel失败,请联系网站管理员!");
  623. }
  624. finally
  625. {
  626. if (wb != null)
  627. {
  628. try
  629. {
  630. wb.close();
  631. }
  632. catch (IOException e1)
  633. {
  634. e1.printStackTrace();
  635. }
  636. }
  637. if (out != null)
  638. {
  639. try
  640. {
  641. out.close();
  642. }
  643. catch (IOException e1)
  644. {
  645. e1.printStackTrace();
  646. }
  647. }
  648. }
  649. }
  650. /**
  651. * 单票分析费用导入到excel表单
  652. *
  653. * @return 结果
  654. */
  655. public AjaxResult singleAnalysisFeesExportExcel()
  656. {
  657. OutputStream out = null;
  658. try
  659. {
  660. // 取出一共有多少个sheet.
  661. double sheetNo = Math.ceil(list.size() / sheetSize);
  662. for (int index = 0; index <= sheetNo; index++)
  663. {
  664. createSheet(sheetNo, index);
  665. // 产生一行
  666. Row row = sheet.createRow(0);
  667. int column = 0;
  668. // 写入各个字段的列头名称
  669. for (Object[] os : fields)
  670. {
  671. Excel excel = (Excel) os[1];
  672. this.createCell(excel, row, column++);
  673. }
  674. if (Type.EXPORT.equals(type))
  675. {
  676. fillExcelData(index, row);
  677. addStatisticsRow();
  678. }
  679. }
  680. Row row = sheet.createRow(list.size() + 1);
  681. Cell cell;// 单元格
  682. String colString;//长度转成ABC后的列
  683. String sumString;//求和公式
  684. Integer[] line = {3, 5};
  685. cell = row.createCell(0);// 创建单元格
  686. cell.setCellValue("合计:");
  687. int totalRows = sheet.getPhysicalNumberOfRows();
  688. for (Integer l : line) {
  689. cell = row.createCell(l);// 创建单元格
  690. cell.setCellStyle(styles.get("total"));// 设置单元格样式
  691. colString = CellReference.convertNumToColString(l); //长度转成ABC列
  692. //求和公式 求i9至i12单元格的总和
  693. sumString = "SUM(" + colString + "2:" + colString + (totalRows-1) + ")";
  694. cell.setCellFormula(sumString);// 把公式塞入合计列
  695. }
  696. wb.setForceFormulaRecalculation(true);
  697. String filename = encodingFilename(sheetName);
  698. out = new FileOutputStream(getAbsoluteFile(filename));
  699. wb.write(out);
  700. return AjaxResult.success(filename);
  701. }
  702. catch (Exception e)
  703. {
  704. log.error("导出Excel异常{}", e.getMessage());
  705. throw new CustomException("导出Excel失败,请联系网站管理员!");
  706. }
  707. finally
  708. {
  709. if (wb != null)
  710. {
  711. try
  712. {
  713. wb.close();
  714. }
  715. catch (IOException e1)
  716. {
  717. e1.printStackTrace();
  718. }
  719. }
  720. if (out != null)
  721. {
  722. try
  723. {
  724. out.close();
  725. }
  726. catch (IOException e1)
  727. {
  728. e1.printStackTrace();
  729. }
  730. }
  731. }
  732. }
  733. /**
  734. * 填充excel数据
  735. *
  736. * @param index 序号
  737. * @param row 单元格行
  738. */
  739. public void fillExcelData(int index, Row row)
  740. {
  741. int startNo = index * sheetSize;
  742. int endNo = Math.min(startNo + sheetSize, list.size());
  743. for (int i = startNo; i < endNo; i++)
  744. {
  745. row = sheet.createRow(i + 1 - startNo);
  746. // 得到导出对象.
  747. T vo = (T) list.get(i);
  748. int column = 0;
  749. for (Object[] os : fields)
  750. {
  751. Field field = (Field) os[0];
  752. Excel excel = (Excel) os[1];
  753. // 设置实体类私有属性可访问
  754. field.setAccessible(true);
  755. this.addCell(excel, row, vo, field, column++);
  756. }
  757. }
  758. }
  759. /**
  760. * 创建表格样式
  761. *
  762. * @param wb 工作薄对象
  763. * @return 样式列表
  764. */
  765. private Map<String, CellStyle> createStyles(Workbook wb)
  766. {
  767. // 写入各条记录,每条记录对应excel表中的一行
  768. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  769. CellStyle style = wb.createCellStyle();
  770. style.setAlignment(HorizontalAlignment.CENTER);
  771. style.setVerticalAlignment(VerticalAlignment.CENTER);
  772. style.setBorderRight(BorderStyle.THIN);
  773. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  774. style.setBorderLeft(BorderStyle.THIN);
  775. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  776. style.setBorderTop(BorderStyle.THIN);
  777. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  778. style.setBorderBottom(BorderStyle.THIN);
  779. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  780. Font dataFont = wb.createFont();
  781. dataFont.setFontName("Arial");
  782. dataFont.setFontHeightInPoints((short) 10);
  783. style.setFont(dataFont);
  784. styles.put("data", style);
  785. style = wb.createCellStyle();
  786. style.cloneStyleFrom(styles.get("data"));
  787. style.setAlignment(HorizontalAlignment.CENTER);
  788. style.setVerticalAlignment(VerticalAlignment.CENTER);
  789. style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
  790. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  791. Font headerFont = wb.createFont();
  792. headerFont.setFontName("Arial");
  793. headerFont.setFontHeightInPoints((short) 10);
  794. headerFont.setBold(true);
  795. headerFont.setColor(IndexedColors.WHITE.getIndex());
  796. style.setFont(headerFont);
  797. styles.put("header", style);
  798. style = wb.createCellStyle();
  799. style.cloneStyleFrom(styles.get("data"));
  800. style.setAlignment(HorizontalAlignment.CENTER);
  801. style.setVerticalAlignment(VerticalAlignment.CENTER);
  802. Font totalFont = wb.createFont();
  803. totalFont.setFontName("Arial");
  804. totalFont.setFontHeightInPoints((short) 10);
  805. totalFont.setBold(true);
  806. style.setFont(totalFont);
  807. styles.put("total", style);
  808. style = wb.createCellStyle();
  809. style.cloneStyleFrom(styles.get("data"));
  810. style.setAlignment(HorizontalAlignment.LEFT);
  811. styles.put("data1", style);
  812. style = wb.createCellStyle();
  813. style.cloneStyleFrom(styles.get("data"));
  814. style.setAlignment(HorizontalAlignment.CENTER);
  815. styles.put("data2", style);
  816. style = wb.createCellStyle();
  817. style.cloneStyleFrom(styles.get("data"));
  818. style.setAlignment(HorizontalAlignment.RIGHT);
  819. styles.put("data3", style);
  820. return styles;
  821. }
  822. /**
  823. * 创建单元格
  824. */
  825. public Cell createCell(Excel attr, Row row, int column)
  826. {
  827. // 创建列
  828. Cell cell = row.createCell(column);
  829. // 写入列信息
  830. cell.setCellValue(attr.name());
  831. setDataValidation(attr, row, column);
  832. cell.setCellStyle(styles.get("header"));
  833. return cell;
  834. }
  835. /**
  836. * 设置单元格信息
  837. *
  838. * @param value 单元格值
  839. * @param attr 注解相关
  840. * @param cell 单元格信息
  841. */
  842. public void setCellVo(Object value, Excel attr, Cell cell)
  843. {
  844. if (ColumnType.STRING == attr.cellType())
  845. {
  846. cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
  847. }
  848. else if (ColumnType.NUMERIC == attr.cellType())
  849. {
  850. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  851. }
  852. }
  853. /**
  854. * 创建表格样式
  855. */
  856. public void setDataValidation(Excel attr, Row row, int column)
  857. {
  858. if (attr.name().indexOf("注:") >= 0)
  859. {
  860. sheet.setColumnWidth(column, 6000);
  861. }
  862. else
  863. {
  864. // 设置列宽
  865. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  866. row.setHeight((short) (attr.height() * 20));
  867. }
  868. // 如果设置了提示信息则鼠标放上去提示.
  869. if (StringUtils.isNotEmpty(attr.prompt()))
  870. {
  871. // 这里默认设了2-101列提示.
  872. setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
  873. }
  874. // 如果设置了combo属性则本列只能选择不能输入
  875. if (attr.combo().length > 0)
  876. {
  877. // 这里默认设了2-101列只能选择不能输入.
  878. setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
  879. }
  880. }
  881. /**
  882. * 添加单元格
  883. */
  884. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  885. {
  886. Cell cell = null;
  887. try
  888. {
  889. // 设置行高
  890. row.setHeight((short) (attr.height() * 20));
  891. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  892. if (attr.isExport())
  893. {
  894. // 创建cell
  895. cell = row.createCell(column);
  896. int align = attr.align().value();
  897. cell.setCellStyle(styles.get("data" + (align >= 1 && align <= 3 ? align : "")));
  898. // 用于读取对象中的属性
  899. Object value = getTargetValue(vo, field, attr);
  900. String dateFormat = attr.dateFormat();
  901. String readConverterExp = attr.readConverterExp();
  902. String separator = attr.separator();
  903. String dictType = attr.dictType();
  904. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  905. {
  906. cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
  907. }
  908. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  909. {
  910. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  911. }
  912. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  913. {
  914. cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
  915. }
  916. else if (value instanceof BigDecimal) {
  917. double doubleVal = ((BigDecimal) value).doubleValue();
  918. cell.setCellValue(doubleVal);
  919. }
  920. else if (value instanceof Integer && -1 != attr.sort())
  921. {
  922. cell.setCellValue((Integer) value);
  923. }
  924. else
  925. {
  926. // 设置列类型
  927. setCellVo(value, attr, cell);
  928. }
  929. addStatisticsData(column, Convert.toStr(value), attr);
  930. }
  931. }
  932. catch (Exception e)
  933. {
  934. log.error("导出Excel失败{}", e);
  935. }
  936. return cell;
  937. }
  938. /**
  939. * 设置 POI XSSFSheet 单元格提示
  940. *
  941. * @param sheet 表单
  942. * @param promptTitle 提示标题
  943. * @param promptContent 提示内容
  944. * @param firstRow 开始行
  945. * @param endRow 结束行
  946. * @param firstCol 开始列
  947. * @param endCol 结束列
  948. */
  949. public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
  950. int firstCol, int endCol)
  951. {
  952. DataValidationHelper helper = sheet.getDataValidationHelper();
  953. DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
  954. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  955. DataValidation dataValidation = helper.createValidation(constraint, regions);
  956. dataValidation.createPromptBox(promptTitle, promptContent);
  957. dataValidation.setShowPromptBox(true);
  958. sheet.addValidationData(dataValidation);
  959. }
  960. /**
  961. * 设置某些列的值只能输入预制的数据,显示下拉框.
  962. *
  963. * @param sheet 要设置的sheet.
  964. * @param textlist 下拉框显示的内容
  965. * @param firstRow 开始行
  966. * @param endRow 结束行
  967. * @param firstCol 开始列
  968. * @param endCol 结束列
  969. * @return 设置好的sheet.
  970. */
  971. public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol)
  972. {
  973. DataValidationHelper helper = sheet.getDataValidationHelper();
  974. // 加载下拉列表内容
  975. DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
  976. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  977. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  978. // 数据有效性对象
  979. DataValidation dataValidation = helper.createValidation(constraint, regions);
  980. // 处理Excel兼容性问题
  981. if (dataValidation instanceof XSSFDataValidation)
  982. {
  983. dataValidation.setSuppressDropDownArrow(true);
  984. dataValidation.setShowErrorBox(true);
  985. }
  986. else
  987. {
  988. dataValidation.setSuppressDropDownArrow(false);
  989. }
  990. sheet.addValidationData(dataValidation);
  991. }
  992. /**
  993. * 解析导出值 0=男,1=女,2=未知
  994. *
  995. * @param propertyValue 参数值
  996. * @param converterExp 翻译注解
  997. * @param separator 分隔符
  998. * @return 解析后值
  999. */
  1000. public static String convertByExp(String propertyValue, String converterExp, String separator)
  1001. {
  1002. StringBuilder propertyString = new StringBuilder();
  1003. String[] convertSource = converterExp.split(",");
  1004. for (String item : convertSource)
  1005. {
  1006. String[] itemArray = item.split("=");
  1007. if (StringUtils.containsAny(separator, propertyValue))
  1008. {
  1009. for (String value : propertyValue.split(separator))
  1010. {
  1011. if (itemArray[0].equals(value))
  1012. {
  1013. propertyString.append(itemArray[1] + separator);
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. else
  1019. {
  1020. if (itemArray[0].equals(propertyValue))
  1021. {
  1022. return itemArray[1];
  1023. }
  1024. }
  1025. }
  1026. return StringUtils.stripEnd(propertyString.toString(), separator);
  1027. }
  1028. /**
  1029. * 反向解析值 男=0,女=1,未知=2
  1030. *
  1031. * @param propertyValue 参数值
  1032. * @param converterExp 翻译注解
  1033. * @param separator 分隔符
  1034. * @return 解析后值
  1035. */
  1036. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  1037. {
  1038. StringBuilder propertyString = new StringBuilder();
  1039. String[] convertSource = converterExp.split(",");
  1040. for (String item : convertSource)
  1041. {
  1042. String[] itemArray = item.split("=");
  1043. if (StringUtils.containsAny(separator, propertyValue))
  1044. {
  1045. for (String value : propertyValue.split(separator))
  1046. {
  1047. if (itemArray[1].equals(value))
  1048. {
  1049. propertyString.append(itemArray[0] + separator);
  1050. break;
  1051. }
  1052. }
  1053. }
  1054. else
  1055. {
  1056. if (itemArray[1].equals(propertyValue))
  1057. {
  1058. return itemArray[0];
  1059. }
  1060. }
  1061. }
  1062. return StringUtils.stripEnd(propertyString.toString(), separator);
  1063. }
  1064. /**
  1065. * 解析字典值
  1066. *
  1067. * @param dictValue 字典值
  1068. * @param dictType 字典类型
  1069. * @param separator 分隔符
  1070. * @return 字典标签
  1071. */
  1072. public static String convertDictByExp(String dictValue, String dictType, String separator)
  1073. {
  1074. return DictUtils.getDictLabel(dictType, dictValue, separator);
  1075. }
  1076. /**
  1077. * 反向解析值字典值
  1078. *
  1079. * @param dictLabel 字典标签
  1080. * @param dictType 字典类型
  1081. * @param separator 分隔符
  1082. * @return 字典值
  1083. */
  1084. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  1085. {
  1086. return DictUtils.getDictValue(dictType, dictLabel, separator);
  1087. }
  1088. /**
  1089. * 合计统计信息
  1090. */
  1091. private void addStatisticsData(Integer index, String text, Excel entity)
  1092. {
  1093. if (entity != null && entity.isStatistics())
  1094. {
  1095. Double temp = 0D;
  1096. if (!statistics.containsKey(index))
  1097. {
  1098. statistics.put(index, temp);
  1099. }
  1100. try
  1101. {
  1102. if (StringUtils.isNotEmpty(text))
  1103. {
  1104. temp = Double.valueOf(text);
  1105. }
  1106. }
  1107. catch (NumberFormatException e)
  1108. {
  1109. }
  1110. statistics.put(index, statistics.get(index) + temp);
  1111. }
  1112. }
  1113. /**
  1114. * 创建统计行
  1115. */
  1116. public void addStatisticsRow()
  1117. {
  1118. if (statistics.size() > 0)
  1119. {
  1120. Cell cell = null;
  1121. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  1122. Set<Integer> keys = statistics.keySet();
  1123. for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i ++)
  1124. {
  1125. cell = row.createCell(i);
  1126. cell.setCellStyle(styles.get("total"));
  1127. }
  1128. int temp = 16384;
  1129. for (Integer key : keys)
  1130. {
  1131. if (temp > key)
  1132. {
  1133. temp = key;
  1134. }
  1135. row.getCell(key).setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  1136. }
  1137. row.getCell(temp - 1).setCellValue("合计");
  1138. statistics.clear();
  1139. }
  1140. }
  1141. /**
  1142. * 编码文件名
  1143. */
  1144. public String encodingFilename(String filename)
  1145. {
  1146. // filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
  1147. filename = filename + ".xlsx";
  1148. return filename;
  1149. }
  1150. /**
  1151. * 获取下载路径
  1152. *
  1153. * @param filename 文件名称
  1154. */
  1155. public String getAbsoluteFile(String filename)
  1156. {
  1157. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  1158. File desc = new File(downloadPath);
  1159. if (!desc.getParentFile().exists())
  1160. {
  1161. desc.getParentFile().mkdirs();
  1162. }
  1163. return downloadPath;
  1164. }
  1165. /**
  1166. * 获取bean中的属性值
  1167. *
  1168. * @param vo 实体对象
  1169. * @param field 字段
  1170. * @param excel 注解
  1171. * @return 最终的属性值
  1172. * @throws Exception
  1173. */
  1174. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  1175. {
  1176. Object o = field.get(vo);
  1177. if (StringUtils.isNotEmpty(excel.targetAttr()))
  1178. {
  1179. String target = excel.targetAttr();
  1180. if (target.indexOf(".") > -1)
  1181. {
  1182. String[] targets = target.split("[.]");
  1183. for (String name : targets)
  1184. {
  1185. o = getValue(o, name);
  1186. }
  1187. }
  1188. else
  1189. {
  1190. o = getValue(o, target);
  1191. }
  1192. }
  1193. return o;
  1194. }
  1195. /**
  1196. * 以类的属性的get方法方法形式获取值
  1197. *
  1198. * @param o
  1199. * @param name
  1200. * @return value
  1201. * @throws Exception
  1202. */
  1203. private Object getValue(Object o, String name) throws Exception
  1204. {
  1205. if (StringUtils.isNotEmpty(name))
  1206. {
  1207. Class<?> clazz = o.getClass();
  1208. Field field = clazz.getDeclaredField(name);
  1209. field.setAccessible(true);
  1210. o = field.get(o);
  1211. }
  1212. return o;
  1213. }
  1214. /**
  1215. * 得到所有定义字段
  1216. */
  1217. private void createExcelField()
  1218. {
  1219. this.fields = new ArrayList<Object[]>();
  1220. List<Field> tempFields = new ArrayList<>();
  1221. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  1222. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  1223. for (Field field : tempFields)
  1224. {
  1225. // 单注解
  1226. if (field.isAnnotationPresent(Excel.class))
  1227. {
  1228. putToField(field, field.getAnnotation(Excel.class));
  1229. }
  1230. // 多注解
  1231. if (field.isAnnotationPresent(Excels.class))
  1232. {
  1233. Excels attrs = field.getAnnotation(Excels.class);
  1234. Excel[] excels = attrs.value();
  1235. for (Excel excel : excels)
  1236. {
  1237. putToField(field, excel);
  1238. }
  1239. }
  1240. }
  1241. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  1242. }
  1243. /**
  1244. * 放到字段集合中
  1245. */
  1246. private void putToField(Field field, Excel attr)
  1247. {
  1248. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1249. {
  1250. this.fields.add(new Object[] { field, attr });
  1251. }
  1252. }
  1253. /**
  1254. * 创建一个工作簿
  1255. */
  1256. public void createWorkbook()
  1257. {
  1258. this.wb = new SXSSFWorkbook(500);
  1259. }
  1260. /**
  1261. * 创建工作表
  1262. *
  1263. * @param sheetNo sheet数量
  1264. * @param index 序号
  1265. */
  1266. public void createSheet(double sheetNo, int index)
  1267. {
  1268. this.sheet = wb.createSheet();
  1269. this.styles = createStyles(wb);
  1270. // 设置工作表的名称.
  1271. if (sheetNo == 0)
  1272. {
  1273. wb.setSheetName(index, sheetName);
  1274. }
  1275. else
  1276. {
  1277. wb.setSheetName(index, sheetName + index);
  1278. }
  1279. }
  1280. /**
  1281. * 获取单元格值
  1282. *
  1283. * @param row 获取的行
  1284. * @param column 获取单元格列号
  1285. * @return 单元格值
  1286. */
  1287. public Object getCellValue(Row row, int column)
  1288. {
  1289. if (row == null)
  1290. {
  1291. return row;
  1292. }
  1293. Object val = "";
  1294. try
  1295. {
  1296. Cell cell = row.getCell(column);
  1297. if (StringUtils.isNotNull(cell))
  1298. {
  1299. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  1300. {
  1301. val = cell.getNumericCellValue();
  1302. if (DateUtil.isCellDateFormatted(cell))
  1303. {
  1304. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  1305. }
  1306. else
  1307. {
  1308. if ((Double) val % 1 > 0)
  1309. {
  1310. val = new BigDecimal(val.toString());
  1311. }
  1312. else
  1313. {
  1314. val = new DecimalFormat("0").format(val);
  1315. }
  1316. }
  1317. }
  1318. else if (cell.getCellType() == CellType.STRING)
  1319. {
  1320. val = cell.getStringCellValue();
  1321. }
  1322. else if (cell.getCellType() == CellType.BOOLEAN)
  1323. {
  1324. val = cell.getBooleanCellValue();
  1325. }
  1326. else if (cell.getCellType() == CellType.ERROR)
  1327. {
  1328. val = cell.getErrorCellValue();
  1329. }
  1330. }
  1331. }
  1332. catch (Exception e)
  1333. {
  1334. return val;
  1335. }
  1336. return val;
  1337. }
  1338. }