ExcelUtil.java 45 KB

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