NewExcelUtil.java 31 KB

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