ExcelUtil.java 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412
  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, 12, 13};
  578. Integer[] line = {7, 8, 10, 11, 12, 13, 16, 17};
  579. cell = row.createCell(0);// 创建单元格
  580. cell.setCellValue("合计:");
  581. int totalRows = sheet.getPhysicalNumberOfRows();
  582. for (Integer l : line) {
  583. cell = row.createCell(l);// 创建单元格
  584. cell.setCellStyle(styles.get("total"));// 设置单元格样式
  585. colString = CellReference.convertNumToColString(l); //长度转成ABC列
  586. sumString = "SUM(" + colString + "2:" + colString + (totalRows-1) + ")";
  587. // 注掉下方代码,避免导出 excel 时,出现数据被除以 1000 的情况
  588. //求和公式 求i9至i12单元格的总和
  589. /*if (l == 8 || l == 11) {
  590. sumString = "SUM(" + colString + "2:" + colString + (totalRows-1) + ") / 1000";
  591. } else {
  592. sumString = "SUM(" + colString + "2:" + colString + (totalRows-1) + ")";
  593. }*/
  594. cell.setCellFormula(sumString);// 把公式塞入合计列
  595. }
  596. wb.setForceFormulaRecalculation(true);
  597. String mblno = "", corpName = "", goodsName = "";
  598. if (map.containsKey("mblno")) {
  599. mblno = map.get("mblno").toString();
  600. }
  601. if (map.containsKey("corpName")) {
  602. corpName = map.get("corpName").toString();
  603. }
  604. if (map.containsKey("goodsName")) {
  605. goodsName = map.get("goodsName").toString();
  606. }
  607. Row primaryRow = sheet.createRow(list.size() + 2);
  608. primaryRow.createCell(0).setCellValue("货主:");
  609. cell = primaryRow.createCell(1);// 创建单元格
  610. cell.setCellValue(corpName);
  611. primaryRow.createCell(2).setCellValue("提单号:");
  612. cell = primaryRow.createCell(3);// 创建单元格
  613. cell.setCellValue(mblno);
  614. primaryRow.createCell(4).setCellValue("品名:");
  615. cell = primaryRow.createCell(5);// 创建单元格
  616. cell.setCellValue(goodsName);
  617. String filename = encodingFilename(sheetName);
  618. out = new FileOutputStream(getAbsoluteFile(filename));
  619. wb.write(out);
  620. return AjaxResult.success(filename);
  621. }
  622. catch (Exception e)
  623. {
  624. log.error("导出Excel异常{}", e.getMessage());
  625. throw new CustomException("导出Excel失败,请联系网站管理员!");
  626. }
  627. finally
  628. {
  629. if (wb != null)
  630. {
  631. try
  632. {
  633. wb.close();
  634. }
  635. catch (IOException e1)
  636. {
  637. e1.printStackTrace();
  638. }
  639. }
  640. if (out != null)
  641. {
  642. try
  643. {
  644. out.close();
  645. }
  646. catch (IOException e1)
  647. {
  648. e1.printStackTrace();
  649. }
  650. }
  651. }
  652. }
  653. /**
  654. * 单票分析费用导入到excel表单
  655. *
  656. * @return 结果
  657. */
  658. public AjaxResult singleAnalysisFeesExportExcel()
  659. {
  660. OutputStream out = null;
  661. try
  662. {
  663. // 取出一共有多少个sheet.
  664. double sheetNo = Math.ceil(list.size() / sheetSize);
  665. for (int index = 0; index <= sheetNo; index++)
  666. {
  667. createSheet(sheetNo, index);
  668. // 产生一行
  669. Row row = sheet.createRow(0);
  670. int column = 0;
  671. // 写入各个字段的列头名称
  672. for (Object[] os : fields)
  673. {
  674. Excel excel = (Excel) os[1];
  675. this.createCell(excel, row, column++);
  676. }
  677. if (Type.EXPORT.equals(type))
  678. {
  679. fillExcelData(index, row);
  680. addStatisticsRow();
  681. }
  682. }
  683. Row row = sheet.createRow(list.size() + 1);
  684. Cell cell;// 单元格
  685. String colString;//长度转成ABC后的列
  686. String sumString;//求和公式
  687. Integer[] line = {5, 7};
  688. cell = row.createCell(0);// 创建单元格
  689. cell.setCellValue("合计:");
  690. int totalRows = sheet.getPhysicalNumberOfRows();
  691. for (Integer l : line) {
  692. cell = row.createCell(l);// 创建单元格
  693. cell.setCellStyle(styles.get("total"));// 设置单元格样式
  694. colString = CellReference.convertNumToColString(l); //长度转成ABC列
  695. //求和公式 求i9至i12单元格的总和
  696. sumString = "SUM(" + colString + "2:" + colString + (totalRows-1) + ")";
  697. cell.setCellFormula(sumString);// 把公式塞入合计列
  698. }
  699. wb.setForceFormulaRecalculation(true);
  700. String filename = encodingFilename(sheetName);
  701. out = new FileOutputStream(getAbsoluteFile(filename));
  702. wb.write(out);
  703. return AjaxResult.success(filename);
  704. }
  705. catch (Exception e)
  706. {
  707. log.error("导出Excel异常{}", e.getMessage());
  708. throw new CustomException("导出Excel失败,请联系网站管理员!");
  709. }
  710. finally
  711. {
  712. if (wb != null)
  713. {
  714. try
  715. {
  716. wb.close();
  717. }
  718. catch (IOException e1)
  719. {
  720. e1.printStackTrace();
  721. }
  722. }
  723. if (out != null)
  724. {
  725. try
  726. {
  727. out.close();
  728. }
  729. catch (IOException e1)
  730. {
  731. e1.printStackTrace();
  732. }
  733. }
  734. }
  735. }
  736. /**
  737. * 填充excel数据
  738. *
  739. * @param index 序号
  740. * @param row 单元格行
  741. */
  742. public void fillExcelData(int index, Row row)
  743. {
  744. int startNo = index * sheetSize;
  745. int endNo = Math.min(startNo + sheetSize, list.size());
  746. for (int i = startNo; i < endNo; i++)
  747. {
  748. row = sheet.createRow(i + 1 - startNo);
  749. // 得到导出对象.
  750. T vo = (T) list.get(i);
  751. int column = 0;
  752. for (Object[] os : fields)
  753. {
  754. Field field = (Field) os[0];
  755. Excel excel = (Excel) os[1];
  756. // 设置实体类私有属性可访问
  757. field.setAccessible(true);
  758. this.addCell(excel, row, vo, field, column++);
  759. }
  760. }
  761. }
  762. /**
  763. * 创建表格样式
  764. *
  765. * @param wb 工作薄对象
  766. * @return 样式列表
  767. */
  768. private Map<String, CellStyle> createStyles(Workbook wb)
  769. {
  770. // 写入各条记录,每条记录对应excel表中的一行
  771. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  772. CellStyle style = wb.createCellStyle();
  773. style.setAlignment(HorizontalAlignment.CENTER);
  774. style.setVerticalAlignment(VerticalAlignment.CENTER);
  775. style.setBorderRight(BorderStyle.THIN);
  776. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  777. style.setBorderLeft(BorderStyle.THIN);
  778. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  779. style.setBorderTop(BorderStyle.THIN);
  780. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  781. style.setBorderBottom(BorderStyle.THIN);
  782. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  783. Font dataFont = wb.createFont();
  784. dataFont.setFontName("Arial");
  785. dataFont.setFontHeightInPoints((short) 10);
  786. style.setFont(dataFont);
  787. styles.put("data", style);
  788. style = wb.createCellStyle();
  789. style.cloneStyleFrom(styles.get("data"));
  790. style.setAlignment(HorizontalAlignment.CENTER);
  791. style.setVerticalAlignment(VerticalAlignment.CENTER);
  792. style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
  793. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  794. Font headerFont = wb.createFont();
  795. headerFont.setFontName("Arial");
  796. headerFont.setFontHeightInPoints((short) 10);
  797. headerFont.setBold(true);
  798. headerFont.setColor(IndexedColors.WHITE.getIndex());
  799. style.setFont(headerFont);
  800. styles.put("header", style);
  801. style = wb.createCellStyle();
  802. style.cloneStyleFrom(styles.get("data"));
  803. style.setAlignment(HorizontalAlignment.CENTER);
  804. style.setVerticalAlignment(VerticalAlignment.CENTER);
  805. Font totalFont = wb.createFont();
  806. totalFont.setFontName("Arial");
  807. totalFont.setFontHeightInPoints((short) 10);
  808. totalFont.setBold(true);
  809. style.setFont(totalFont);
  810. styles.put("total", style);
  811. style = wb.createCellStyle();
  812. style.cloneStyleFrom(styles.get("data"));
  813. style.setAlignment(HorizontalAlignment.LEFT);
  814. styles.put("data1", style);
  815. style = wb.createCellStyle();
  816. style.cloneStyleFrom(styles.get("data"));
  817. style.setAlignment(HorizontalAlignment.CENTER);
  818. styles.put("data2", style);
  819. style = wb.createCellStyle();
  820. style.cloneStyleFrom(styles.get("data"));
  821. style.setAlignment(HorizontalAlignment.RIGHT);
  822. styles.put("data3", style);
  823. return styles;
  824. }
  825. /**
  826. * 创建单元格
  827. */
  828. public Cell createCell(Excel attr, Row row, int column)
  829. {
  830. // 创建列
  831. Cell cell = row.createCell(column);
  832. // 写入列信息
  833. cell.setCellValue(attr.name());
  834. setDataValidation(attr, row, column);
  835. cell.setCellStyle(styles.get("header"));
  836. return cell;
  837. }
  838. /**
  839. * 设置单元格信息
  840. *
  841. * @param value 单元格值
  842. * @param attr 注解相关
  843. * @param cell 单元格信息
  844. */
  845. public void setCellVo(Object value, Excel attr, Cell cell)
  846. {
  847. if (ColumnType.STRING == attr.cellType())
  848. {
  849. cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
  850. }
  851. else if (ColumnType.NUMERIC == attr.cellType())
  852. {
  853. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  854. }
  855. }
  856. /**
  857. * 创建表格样式
  858. */
  859. public void setDataValidation(Excel attr, Row row, int column)
  860. {
  861. if (attr.name().indexOf("注:") >= 0)
  862. {
  863. sheet.setColumnWidth(column, 6000);
  864. }
  865. else
  866. {
  867. // 设置列宽
  868. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  869. row.setHeight((short) (attr.height() * 20));
  870. }
  871. // 如果设置了提示信息则鼠标放上去提示.
  872. if (StringUtils.isNotEmpty(attr.prompt()))
  873. {
  874. // 这里默认设了2-101列提示.
  875. setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
  876. }
  877. // 如果设置了combo属性则本列只能选择不能输入
  878. if (attr.combo().length > 0)
  879. {
  880. // 这里默认设了2-101列只能选择不能输入.
  881. setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
  882. }
  883. }
  884. /**
  885. * 添加单元格
  886. */
  887. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  888. {
  889. Cell cell = null;
  890. try
  891. {
  892. // 设置行高
  893. row.setHeight((short) (attr.height() * 20));
  894. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  895. if (attr.isExport())
  896. {
  897. // 创建cell
  898. cell = row.createCell(column);
  899. int align = attr.align().value();
  900. cell.setCellStyle(styles.get("data" + (align >= 1 && align <= 3 ? align : "")));
  901. // 用于读取对象中的属性
  902. Object value = getTargetValue(vo, field, attr);
  903. String dateFormat = attr.dateFormat();
  904. String readConverterExp = attr.readConverterExp();
  905. String separator = attr.separator();
  906. String dictType = attr.dictType();
  907. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  908. {
  909. cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
  910. }
  911. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  912. {
  913. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  914. }
  915. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  916. {
  917. cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
  918. }
  919. else if (value instanceof BigDecimal) {
  920. double doubleVal = ((BigDecimal) value).doubleValue();
  921. cell.setCellValue(doubleVal);
  922. }
  923. else if (value instanceof Integer && -1 != attr.sort())
  924. {
  925. cell.setCellValue((Integer) value);
  926. }
  927. else
  928. {
  929. // 设置列类型
  930. setCellVo(value, attr, cell);
  931. }
  932. addStatisticsData(column, Convert.toStr(value), attr);
  933. }
  934. }
  935. catch (Exception e)
  936. {
  937. log.error("导出Excel失败{}", e);
  938. }
  939. return cell;
  940. }
  941. /**
  942. * 设置 POI XSSFSheet 单元格提示
  943. *
  944. * @param sheet 表单
  945. * @param promptTitle 提示标题
  946. * @param promptContent 提示内容
  947. * @param firstRow 开始行
  948. * @param endRow 结束行
  949. * @param firstCol 开始列
  950. * @param endCol 结束列
  951. */
  952. public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
  953. int firstCol, int endCol)
  954. {
  955. DataValidationHelper helper = sheet.getDataValidationHelper();
  956. DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
  957. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  958. DataValidation dataValidation = helper.createValidation(constraint, regions);
  959. dataValidation.createPromptBox(promptTitle, promptContent);
  960. dataValidation.setShowPromptBox(true);
  961. sheet.addValidationData(dataValidation);
  962. }
  963. /**
  964. * 设置某些列的值只能输入预制的数据,显示下拉框.
  965. *
  966. * @param sheet 要设置的sheet.
  967. * @param textlist 下拉框显示的内容
  968. * @param firstRow 开始行
  969. * @param endRow 结束行
  970. * @param firstCol 开始列
  971. * @param endCol 结束列
  972. * @return 设置好的sheet.
  973. */
  974. public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol)
  975. {
  976. DataValidationHelper helper = sheet.getDataValidationHelper();
  977. // 加载下拉列表内容
  978. DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
  979. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
  980. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  981. // 数据有效性对象
  982. DataValidation dataValidation = helper.createValidation(constraint, regions);
  983. // 处理Excel兼容性问题
  984. if (dataValidation instanceof XSSFDataValidation)
  985. {
  986. dataValidation.setSuppressDropDownArrow(true);
  987. dataValidation.setShowErrorBox(true);
  988. }
  989. else
  990. {
  991. dataValidation.setSuppressDropDownArrow(false);
  992. }
  993. sheet.addValidationData(dataValidation);
  994. }
  995. /**
  996. * 解析导出值 0=男,1=女,2=未知
  997. *
  998. * @param propertyValue 参数值
  999. * @param converterExp 翻译注解
  1000. * @param separator 分隔符
  1001. * @return 解析后值
  1002. */
  1003. public static String convertByExp(String propertyValue, String converterExp, String separator)
  1004. {
  1005. StringBuilder propertyString = new StringBuilder();
  1006. String[] convertSource = converterExp.split(",");
  1007. for (String item : convertSource)
  1008. {
  1009. String[] itemArray = item.split("=");
  1010. if (StringUtils.containsAny(separator, propertyValue))
  1011. {
  1012. for (String value : propertyValue.split(separator))
  1013. {
  1014. if (itemArray[0].equals(value))
  1015. {
  1016. propertyString.append(itemArray[1] + separator);
  1017. break;
  1018. }
  1019. }
  1020. }
  1021. else
  1022. {
  1023. if (itemArray[0].equals(propertyValue))
  1024. {
  1025. return itemArray[1];
  1026. }
  1027. }
  1028. }
  1029. return StringUtils.stripEnd(propertyString.toString(), separator);
  1030. }
  1031. /**
  1032. * 反向解析值 男=0,女=1,未知=2
  1033. *
  1034. * @param propertyValue 参数值
  1035. * @param converterExp 翻译注解
  1036. * @param separator 分隔符
  1037. * @return 解析后值
  1038. */
  1039. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  1040. {
  1041. StringBuilder propertyString = new StringBuilder();
  1042. String[] convertSource = converterExp.split(",");
  1043. for (String item : convertSource)
  1044. {
  1045. String[] itemArray = item.split("=");
  1046. if (StringUtils.containsAny(separator, propertyValue))
  1047. {
  1048. for (String value : propertyValue.split(separator))
  1049. {
  1050. if (itemArray[1].equals(value))
  1051. {
  1052. propertyString.append(itemArray[0] + separator);
  1053. break;
  1054. }
  1055. }
  1056. }
  1057. else
  1058. {
  1059. if (itemArray[1].equals(propertyValue))
  1060. {
  1061. return itemArray[0];
  1062. }
  1063. }
  1064. }
  1065. return StringUtils.stripEnd(propertyString.toString(), separator);
  1066. }
  1067. /**
  1068. * 解析字典值
  1069. *
  1070. * @param dictValue 字典值
  1071. * @param dictType 字典类型
  1072. * @param separator 分隔符
  1073. * @return 字典标签
  1074. */
  1075. public static String convertDictByExp(String dictValue, String dictType, String separator)
  1076. {
  1077. return DictUtils.getDictLabel(dictType, dictValue, separator);
  1078. }
  1079. /**
  1080. * 反向解析值字典值
  1081. *
  1082. * @param dictLabel 字典标签
  1083. * @param dictType 字典类型
  1084. * @param separator 分隔符
  1085. * @return 字典值
  1086. */
  1087. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  1088. {
  1089. return DictUtils.getDictValue(dictType, dictLabel, separator);
  1090. }
  1091. /**
  1092. * 合计统计信息
  1093. */
  1094. private void addStatisticsData(Integer index, String text, Excel entity)
  1095. {
  1096. if (entity != null && entity.isStatistics())
  1097. {
  1098. Double temp = 0D;
  1099. if (!statistics.containsKey(index))
  1100. {
  1101. statistics.put(index, temp);
  1102. }
  1103. try
  1104. {
  1105. if (StringUtils.isNotEmpty(text))
  1106. {
  1107. temp = Double.valueOf(text);
  1108. }
  1109. }
  1110. catch (NumberFormatException e)
  1111. {
  1112. }
  1113. statistics.put(index, statistics.get(index) + temp);
  1114. }
  1115. }
  1116. /**
  1117. * 创建统计行
  1118. */
  1119. public void addStatisticsRow()
  1120. {
  1121. if (statistics.size() > 0)
  1122. {
  1123. Cell cell = null;
  1124. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  1125. Set<Integer> keys = statistics.keySet();
  1126. for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i ++)
  1127. {
  1128. cell = row.createCell(i);
  1129. cell.setCellStyle(styles.get("total"));
  1130. }
  1131. int temp = 16384;
  1132. for (Integer key : keys)
  1133. {
  1134. if (temp > key)
  1135. {
  1136. temp = key;
  1137. }
  1138. row.getCell(key).setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  1139. }
  1140. row.getCell(temp - 1).setCellValue("合计");
  1141. statistics.clear();
  1142. }
  1143. }
  1144. /**
  1145. * 编码文件名
  1146. */
  1147. public String encodingFilename(String filename)
  1148. {
  1149. // filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
  1150. filename = filename + ".xlsx";
  1151. return filename;
  1152. }
  1153. /**
  1154. * 获取下载路径
  1155. *
  1156. * @param filename 文件名称
  1157. */
  1158. public String getAbsoluteFile(String filename)
  1159. {
  1160. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  1161. File desc = new File(downloadPath);
  1162. if (!desc.getParentFile().exists())
  1163. {
  1164. desc.getParentFile().mkdirs();
  1165. }
  1166. return downloadPath;
  1167. }
  1168. /**
  1169. * 获取bean中的属性值
  1170. *
  1171. * @param vo 实体对象
  1172. * @param field 字段
  1173. * @param excel 注解
  1174. * @return 最终的属性值
  1175. * @throws Exception
  1176. */
  1177. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  1178. {
  1179. Object o = field.get(vo);
  1180. if (StringUtils.isNotEmpty(excel.targetAttr()))
  1181. {
  1182. String target = excel.targetAttr();
  1183. if (target.indexOf(".") > -1)
  1184. {
  1185. String[] targets = target.split("[.]");
  1186. for (String name : targets)
  1187. {
  1188. o = getValue(o, name);
  1189. }
  1190. }
  1191. else
  1192. {
  1193. o = getValue(o, target);
  1194. }
  1195. }
  1196. return o;
  1197. }
  1198. /**
  1199. * 以类的属性的get方法方法形式获取值
  1200. *
  1201. * @param o
  1202. * @param name
  1203. * @return value
  1204. * @throws Exception
  1205. */
  1206. private Object getValue(Object o, String name) throws Exception
  1207. {
  1208. if (StringUtils.isNotEmpty(name))
  1209. {
  1210. Class<?> clazz = o.getClass();
  1211. Field field = clazz.getDeclaredField(name);
  1212. field.setAccessible(true);
  1213. o = field.get(o);
  1214. }
  1215. return o;
  1216. }
  1217. /**
  1218. * 得到所有定义字段
  1219. */
  1220. private void createExcelField()
  1221. {
  1222. this.fields = new ArrayList<Object[]>();
  1223. List<Field> tempFields = new ArrayList<>();
  1224. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  1225. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  1226. for (Field field : tempFields)
  1227. {
  1228. // 单注解
  1229. if (field.isAnnotationPresent(Excel.class))
  1230. {
  1231. putToField(field, field.getAnnotation(Excel.class));
  1232. }
  1233. // 多注解
  1234. if (field.isAnnotationPresent(Excels.class))
  1235. {
  1236. Excels attrs = field.getAnnotation(Excels.class);
  1237. Excel[] excels = attrs.value();
  1238. for (Excel excel : excels)
  1239. {
  1240. putToField(field, excel);
  1241. }
  1242. }
  1243. }
  1244. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  1245. }
  1246. /**
  1247. * 放到字段集合中
  1248. */
  1249. private void putToField(Field field, Excel attr)
  1250. {
  1251. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1252. {
  1253. this.fields.add(new Object[] { field, attr });
  1254. }
  1255. }
  1256. /**
  1257. * 创建一个工作簿
  1258. */
  1259. public void createWorkbook()
  1260. {
  1261. this.wb = new SXSSFWorkbook(500);
  1262. }
  1263. /**
  1264. * 创建工作表
  1265. *
  1266. * @param sheetNo sheet数量
  1267. * @param index 序号
  1268. */
  1269. public void createSheet(double sheetNo, int index)
  1270. {
  1271. this.sheet = wb.createSheet();
  1272. this.styles = createStyles(wb);
  1273. // 设置工作表的名称.
  1274. if (sheetNo == 0)
  1275. {
  1276. wb.setSheetName(index, sheetName);
  1277. }
  1278. else
  1279. {
  1280. wb.setSheetName(index, sheetName + index);
  1281. }
  1282. }
  1283. /**
  1284. * 获取单元格值
  1285. *
  1286. * @param row 获取的行
  1287. * @param column 获取单元格列号
  1288. * @return 单元格值
  1289. */
  1290. public Object getCellValue(Row row, int column)
  1291. {
  1292. if (row == null)
  1293. {
  1294. return row;
  1295. }
  1296. Object val = "";
  1297. try
  1298. {
  1299. Cell cell = row.getCell(column);
  1300. if (StringUtils.isNotNull(cell))
  1301. {
  1302. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  1303. {
  1304. val = cell.getNumericCellValue();
  1305. if (DateUtil.isCellDateFormatted(cell))
  1306. {
  1307. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  1308. }
  1309. else
  1310. {
  1311. if ((Double) val % 1 > 0)
  1312. {
  1313. val = new BigDecimal(val.toString());
  1314. }
  1315. else
  1316. {
  1317. val = new DecimalFormat("0").format(val);
  1318. }
  1319. }
  1320. }
  1321. else if (cell.getCellType() == CellType.STRING)
  1322. {
  1323. val = cell.getStringCellValue();
  1324. }
  1325. else if (cell.getCellType() == CellType.BOOLEAN)
  1326. {
  1327. val = cell.getBooleanCellValue();
  1328. }
  1329. else if (cell.getCellType() == CellType.ERROR)
  1330. {
  1331. val = cell.getErrorCellValue();
  1332. }
  1333. }
  1334. }
  1335. catch (Exception e)
  1336. {
  1337. return val;
  1338. }
  1339. return val;
  1340. }
  1341. }