NewExcelUtil.java 29 KB

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