1. package com.bonc.system.utils.excel;
    2. import cn.hutool.core.convert.Convert;
    3. import cn.hutool.core.exceptions.UtilException;
    4. import cn.hutool.core.io.FileUtil;
    5. import cn.hutool.core.util.ObjectUtil;
    6. import com.bonc.common.config.ProjectConfig;
    7. import com.bonc.common.utils.DateUtils;
    8. import com.bonc.common.utils.ReflectUtils;
    9. import com.bonc.common.utils.file.FileUtils;
    10. import com.bonc.common.utils.file.ImageUtils;
    11. import com.bonc.system.utils.DictUtils;
    12. import com.bonc.system.utils.excel.annotations.Excel;
    13. import com.bonc.system.utils.excel.annotations.Excel.ColumnType;
    14. import com.bonc.system.utils.excel.annotations.Excel.Type;
    15. import com.bonc.system.utils.excel.annotations.Excels;
    16. import org.apache.commons.lang3.StringUtils;
    17. import org.apache.poi.hssf.usermodel.*;
    18. import org.apache.poi.ooxml.POIXMLDocumentPart;
    19. import org.apache.poi.ss.usermodel.*;
    20. import org.apache.poi.ss.util.CellRangeAddress;
    21. import org.apache.poi.ss.util.CellRangeAddressList;
    22. import org.apache.poi.util.IOUtils;
    23. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
    24. import org.apache.poi.xssf.usermodel.*;
    25. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
    26. import org.slf4j.Logger;
    27. import org.slf4j.LoggerFactory;
    28. import javax.servlet.http.HttpServletResponse;
    29. import java.io.*;
    30. import java.lang.reflect.Field;
    31. import java.lang.reflect.Method;
    32. import java.math.BigDecimal;
    33. import java.nio.charset.StandardCharsets;
    34. import java.text.DecimalFormat;
    35. import java.util.*;
    36. import java.util.stream.Collectors;
    37. /**
    38. * <p>
    39. * Excel相关处理
    40. * </p>
    41. *
    42. * @author xupu
    43. * @since 2021/12/27 21:12
    44. */
    45. public class ExcelUtil<T> {
    46. // 挂在项目的某文件夹下
    47. public static final String REPORT_PATH = "templates" + File.separator;
    48. /**
    49. * Excel sheet最大行数,默认65536
    50. */
    51. public static final int sheetSize = 65536;
    52. private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
    53. /**
    54. * 数字格式
    55. */
    56. private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
    57. /**
    58. * 实体对象
    59. */
    60. public Class<T> clazz;
    61. /**
    62. * 工作表名称
    63. */
    64. private String sheetName;
    65. /**
    66. * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
    67. */
    68. private Type type;
    69. /**
    70. * 工作薄对象
    71. */
    72. private Workbook wb;
    73. /**
    74. * 工作表对象
    75. */
    76. private Sheet sheet;
    77. /**
    78. * 样式列表
    79. */
    80. private Map<String, CellStyle> styles;
    81. /**
    82. * 导入导出数据列表
    83. */
    84. private List<T> list;
    85. /**
    86. * 注解列表
    87. */
    88. private List<Object[]> fields;
    89. /**
    90. * 当前行号
    91. */
    92. private int rowNum;
    93. /**
    94. * 标题
    95. */
    96. private String title;
    97. /**
    98. * 最大高度
    99. */
    100. private short maxHeight;
    101. /**
    102. * 统计列表
    103. */
    104. private Map<Integer, Double> statistics = new HashMap<>();
    105. public ExcelUtil(Class<T> clazz) {
    106. this.clazz = clazz;
    107. }
    108. /**
    109. * 获取画布
    110. */
    111. public static Drawing<?> getDrawingPatriarch(Sheet sheet) {
    112. if (sheet.getDrawingPatriarch() == null) {
    113. sheet.createDrawingPatriarch();
    114. }
    115. return sheet.getDrawingPatriarch();
    116. }
    117. /**
    118. * 解析导出值 0=男,1=女,2=未知
    119. *
    120. * @param propertyValue 参数值
    121. * @param converterExp 翻译注解
    122. * @param separator 分隔符
    123. * @return 解析后值
    124. */
    125. public static String convertByExp(String propertyValue, String converterExp, String separator) {
    126. StringBuilder propertyString = new StringBuilder();
    127. String[] convertSource = converterExp.split(",");
    128. for (String item : convertSource) {
    129. String[] itemArray = item.split("=");
    130. if (StringUtils.containsAny(separator, propertyValue)) {
    131. for (String value : propertyValue.split(separator)) {
    132. if (itemArray[0].equals(value)) {
    133. propertyString.append(itemArray[1]).append(separator);
    134. break;
    135. }
    136. }
    137. } else {
    138. if (itemArray[0].equals(propertyValue)) {
    139. return itemArray[1];
    140. }
    141. }
    142. }
    143. return StringUtils.stripEnd(propertyString.toString(), separator);
    144. }
    145. /**
    146. * 反向解析值 男=0,女=1,未知=2
    147. *
    148. * @param propertyValue 参数值
    149. * @param converterExp 翻译注解
    150. * @param separator 分隔符
    151. * @return 解析后值
    152. */
    153. public static String reverseByExp(String propertyValue, String converterExp, String separator) {
    154. StringBuilder propertyString = new StringBuilder();
    155. String[] convertSource = converterExp.split(",");
    156. for (String item : convertSource) {
    157. String[] itemArray = item.split("=");
    158. if (StringUtils.containsAny(separator, propertyValue)) {
    159. for (String value : propertyValue.split(separator)) {
    160. if (itemArray[1].equals(value)) {
    161. propertyString.append(itemArray[0]).append(separator);
    162. break;
    163. }
    164. }
    165. } else {
    166. if (itemArray[1].equals(propertyValue)) {
    167. return itemArray[0];
    168. }
    169. }
    170. }
    171. return StringUtils.stripEnd(propertyString.toString(), separator);
    172. }
    173. /**
    174. * 解析字典值
    175. *
    176. * @param dictValue 字典值
    177. * @param dictType 字典类型
    178. * @param separator 分隔符
    179. * @return 字典标签
    180. */
    181. public static String convertDictByExp(String dictValue, String dictType, String separator) {
    182. return DictUtils.getDictLabel(dictType, dictValue, separator);
    183. }
    184. /**
    185. * 反向解析值字典值
    186. *
    187. * @param dictLabel 字典标签
    188. * @param dictType 字典类型
    189. * @param separator 分隔符
    190. * @return 字典值
    191. */
    192. public static String reverseDictByExp(String dictLabel, String dictType, String separator) {
    193. return DictUtils.getDictValue(dictType, dictLabel, separator);
    194. }
    195. /**
    196. * 获取Excel2003图片
    197. *
    198. * @param sheet 当前sheet对象
    199. * @param workbook 工作簿对象
    200. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
    201. */
    202. public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook) {
    203. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
    204. List<HSSFPictureData> pictures = workbook.getAllPictures();
    205. if (!pictures.isEmpty()) {
    206. for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
    207. HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
    208. if (shape instanceof HSSFPicture) {
    209. HSSFPicture pic = (HSSFPicture) shape;
    210. int pictureIndex = pic.getPictureIndex() - 1;
    211. HSSFPictureData picData = pictures.get(pictureIndex);
    212. String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1());
    213. sheetIndexPicMap.put(picIndex, picData);
    214. }
    215. }
    216. return sheetIndexPicMap;
    217. } else {
    218. return sheetIndexPicMap;
    219. }
    220. }
    221. /**
    222. * 获取Excel2007图片
    223. *
    224. * @param sheet 当前sheet对象
    225. * @param workbook 工作簿对象
    226. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
    227. */
    228. public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook) {
    229. Map<String, PictureData> sheetIndexPicMap = new HashMap<>();
    230. for (POIXMLDocumentPart dr : sheet.getRelations()) {
    231. if (dr instanceof XSSFDrawing) {
    232. XSSFDrawing drawing = (XSSFDrawing) dr;
    233. List<XSSFShape> shapes = drawing.getShapes();
    234. for (XSSFShape shape : shapes) {
    235. if (shape instanceof XSSFPicture) {
    236. XSSFPicture pic = (XSSFPicture) shape;
    237. XSSFClientAnchor anchor = pic.getPreferredSize();
    238. CTMarker ctMarker = anchor.getFrom();
    239. String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
    240. sheetIndexPicMap.put(picIndex, pic.getPictureData());
    241. }
    242. }
    243. }
    244. }
    245. return sheetIndexPicMap;
    246. }
    247. public void init(List<T> list, String sheetName, String title, Type type) {
    248. if (list == null) {
    249. list = new ArrayList<>();
    250. }
    251. this.list = list;
    252. this.sheetName = sheetName;
    253. this.type = type;
    254. this.title = title;
    255. createExcelField();
    256. createWorkbook();
    257. createTitle();
    258. }
    259. /**
    260. * 创建excel第一行标题
    261. */
    262. public void createTitle() {
    263. if (StringUtils.isNotEmpty(title)) {
    264. Row titleRow = sheet.createRow(rowNum == 0 ? rowNum++ : 0);
    265. titleRow.setHeightInPoints(30);
    266. Cell titleCell = titleRow.createCell(0);
    267. titleCell.setCellStyle(styles.get("title"));
    268. titleCell.setCellValue(title);
    269. sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(),
    270. this.fields.size() - 1));
    271. }
    272. }
    273. /**
    274. * 对excel表单默认第一个索引名转换成list
    275. *
    276. * @param is 输入流
    277. * @return 转换后集合
    278. */
    279. public List<T> importExcel(InputStream is) throws Exception {
    280. return importExcel(is, 0);
    281. }
    282. /**
    283. * 对excel表单默认第一个索引名转换成list
    284. *
    285. * @param is 输入流
    286. * @param titleNum 标题占用行数
    287. * @return 转换后集合
    288. */
    289. public List<T> importExcel(InputStream is, int titleNum) throws Exception {
    290. return importExcel(StringUtils.EMPTY, is, titleNum);
    291. }
    292. /**
    293. * 对excel表单指定表格索引名转换成list
    294. *
    295. * @param sheetName 表格索引名
    296. * @param titleNum 标题占用行数
    297. * @param is 输入流
    298. * @return 转换后集合
    299. */
    300. public List<T> importExcel(String sheetName, InputStream is, int titleNum) throws Exception {
    301. this.type = Type.IMPORT;
    302. this.wb = WorkbookFactory.create(is);
    303. List<T> list = new ArrayList<T>();
    304. // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
    305. Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0);
    306. if (sheet == null) {
    307. throw new IOException("文件sheet不存在");
    308. }
    309. boolean isXSSFWorkbook = !(wb instanceof HSSFWorkbook);
    310. Map<String, PictureData> pictures;
    311. if (isXSSFWorkbook) {
    312. pictures = getSheetPictures07((XSSFSheet) sheet, (XSSFWorkbook) wb);
    313. } else {
    314. pictures = getSheetPictures03((HSSFSheet) sheet, (HSSFWorkbook) wb);
    315. }
    316. // 获取最后一个非空行的行下标,比如总行数为n,则返回的为n-1
    317. int rows = sheet.getLastRowNum();
    318. if (rows > 0) {
    319. // 定义一个map用于存放excel列的序号和field.
    320. Map<String, Integer> cellMap = new HashMap<>();
    321. // 获取表头
    322. Row heard = sheet.getRow(titleNum);
    323. for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
    324. Cell cell = heard.getCell(i);
    325. if (ObjectUtil.isNotNull(cell)) {
    326. String value = this.getCellValue(heard, i).toString();
    327. cellMap.put(value, i);
    328. } else {
    329. cellMap.put(null, i);
    330. }
    331. }
    332. // 有数据时才处理 得到类的所有field.
    333. List<Object[]> fields = this.getFields();
    334. Map<Integer, Object[]> fieldsMap = new HashMap<>();
    335. for (Object[] objects : fields) {
    336. Excel attr = (Excel) objects[1];
    337. Integer column = cellMap.get(attr.name());
    338. if (column != null) {
    339. fieldsMap.put(column, objects);
    340. }
    341. }
    342. for (int i = titleNum + 1; i <= rows; i++) {
    343. // 从第2行开始取数据,默认第一行是表头.
    344. Row row = sheet.getRow(i);
    345. // 判断当前行是否是空行
    346. if (isRowEmpty(row)) {
    347. continue;
    348. }
    349. T entity = null;
    350. for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet()) {
    351. Object val = this.getCellValue(row, entry.getKey());
    352. // 如果不存在实例则新建.
    353. entity = (entity == null ? clazz.newInstance() : entity);
    354. // 从map中得到对应列的field.
    355. Field field = (Field) entry.getValue()[0];
    356. Excel attr = (Excel) entry.getValue()[1];
    357. // 取得类型,并根据对象类型设置值.
    358. Class<?> fieldType = field.getType();
    359. if (String.class == fieldType) {
    360. String s = Convert.toStr(val);
    361. if (StringUtils.endsWith(s, ".0")) {
    362. val = StringUtils.substringBefore(s, ".0");
    363. } else {
    364. String dateFormat = field.getAnnotation(Excel.class).dateFormat();
    365. if (StringUtils.isNotEmpty(dateFormat)) {
    366. val = DateUtils.parseDateToStr(dateFormat, (Date) val);
    367. } else {
    368. val = Convert.toStr(val);
    369. }
    370. }
    371. } else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val))) {
    372. val = Convert.toInt(val);
    373. } else if (Long.TYPE == fieldType || Long.class == fieldType) {
    374. val = Convert.toLong(val);
    375. } else if (Double.TYPE == fieldType || Double.class == fieldType) {
    376. val = Convert.toDouble(val);
    377. } else if (Float.TYPE == fieldType || Float.class == fieldType) {
    378. val = Convert.toFloat(val);
    379. } else if (BigDecimal.class == fieldType) {
    380. val = Convert.toBigDecimal(val);
    381. } else if (Date.class == fieldType) {
    382. if (val instanceof String) {
    383. val = DateUtils.parseDate((String) val);
    384. } else if (val instanceof Double) {
    385. val = DateUtil.getJavaDate((Double) val);
    386. }
    387. } else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) {
    388. val = Convert.toBool(val, false);
    389. }
    390. if (ObjectUtil.isNotNull(fieldType)) {
    391. String propertyName = field.getName();
    392. if (StringUtils.isNotEmpty(attr.targetAttr())) {
    393. propertyName = field.getName() + "." + attr.targetAttr();
    394. } else if (StringUtils.isNotEmpty(attr.readConverterExp())) {
    395. val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
    396. } else if (StringUtils.isNotEmpty(attr.dictType())) {
    397. val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
    398. } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) {
    399. val = dataFormatHandlerAdapter(val, attr);
    400. } else if (ColumnType.IMAGE == attr.cellType() && ObjectUtil.isNotEmpty(pictures)) {
    401. PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey());
    402. if (image == null) {
    403. val = "";
    404. } else {
    405. byte[] data = image.getData();
    406. val = FileUtils.writeImportBytes(data);
    407. }
    408. }
    409. ReflectUtils.invokeSetter(entity, propertyName, val);
    410. }
    411. }
    412. list.add(entity);
    413. }
    414. }
    415. return list;
    416. }
    417. /**
    418. * 对list数据源将其里面的数据导入到excel表单
    419. *
    420. * @param list 导出数据集合
    421. * @param sheetName 工作表的名称
    422. * @return 结果
    423. */
    424. public String exportExcel(List<T> list, String sheetName) {
    425. return exportExcel(list, sheetName, StringUtils.EMPTY);
    426. }
    427. /**
    428. * 对list数据源将其里面的数据导入到excel表单
    429. *
    430. * @param list 导出数据集合
    431. * @param sheetName 工作表的名称
    432. * @param title 标题
    433. * @return 结果
    434. */
    435. public String exportExcel(List<T> list, String sheetName, String title) {
    436. this.init(list, sheetName, title, Type.EXPORT);
    437. return exportExcel();
    438. }
    439. /**
    440. * 对list数据源将其里面的数据导入到excel表单
    441. *
    442. * @param response 返回数据
    443. * @param list 导出数据集合
    444. * @param sheetName 工作表的名称
    445. * @return 结果
    446. * @throws IOException
    447. */
    448. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName) {
    449. exportExcel(response, list, sheetName, StringUtils.EMPTY);
    450. }
    451. /**
    452. * 对list数据源将其里面的数据导入到excel表单
    453. *
    454. * @param response 返回数据
    455. * @param list 导出数据集合
    456. * @param sheetName 工作表的名称
    457. * @param title 标题
    458. * @return 结果
    459. * @throws IOException
    460. */
    461. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName, String title) {
    462. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    463. response.setHeader("Content-Disposition", "attachment;fileName=" + new String(sheetName.getBytes(), StandardCharsets.UTF_8) + ".xlsx");
    464. response.setCharacterEncoding("utf-8");
    465. this.init(list, sheetName, title, Type.EXPORT);
    466. exportExcel(response);
    467. }
    468. /**
    469. * 对list数据源将其里面的数据导入到excel表单
    470. *
    471. * @param sheetName 工作表的名称
    472. * @return 结果
    473. */
    474. public String importTemplateExcel(String sheetName) {
    475. return importTemplateExcel(sheetName, StringUtils.EMPTY);
    476. }
    477. /**
    478. * 对list数据源将其里面的数据导入到excel表单
    479. *
    480. * @param sheetName 工作表的名称
    481. * @param title 标题
    482. * @return 结果
    483. */
    484. public String importTemplateExcel(String sheetName, String title) {
    485. this.init(null, sheetName, title, Type.IMPORT);
    486. return exportExcel();
    487. }
    488. /**
    489. * 对list数据源将其里面的数据导入到excel表单
    490. *
    491. * @param sheetName 工作表的名称
    492. * @return 结果
    493. */
    494. public void importTemplateExcel(HttpServletResponse response, String sheetName) {
    495. importTemplateExcel(response, sheetName, StringUtils.EMPTY);
    496. }
    497. /**
    498. * 对list数据源将其里面的数据导入到excel表单
    499. *
    500. * @param sheetName 工作表的名称
    501. * @param title 标题
    502. * @return 结果
    503. */
    504. public void importTemplateExcel(HttpServletResponse response, String sheetName, String title) {
    505. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    506. try {
    507. response.setHeader("Content-Disposition",
    508. "attachment;filename=" + new String((sheetName+".xlsx").getBytes(), "utf-8"));
    509. } catch (UnsupportedEncodingException e) {
    510. e.printStackTrace();
    511. }
    512. response.setCharacterEncoding("utf-8");
    513. this.init(null, sheetName, title, Type.IMPORT);
    514. exportExcel(response);
    515. }
    516. /**
    517. * 对list数据源将其里面的数据导入到excel表单
    518. *
    519. * @return 结果
    520. */
    521. public void exportExcel(HttpServletResponse response) {
    522. try {
    523. writeSheet();
    524. wb.write(response.getOutputStream());
    525. } catch (Exception e) {
    526. log.error("导出Excel异常{}", e.getMessage());
    527. } finally {
    528. IOUtils.closeQuietly(wb);
    529. }
    530. }
    531. /**
    532. * 对list数据源将其里面的数据导入到excel表单
    533. *
    534. * @return 下载路径
    535. */
    536. public String exportExcel() {
    537. FileOutputStream fos = null;
    538. String fileName = sheetName + ".xlsx";
    539. try {
    540. fos = new FileOutputStream(REPORT_PATH + fileName);
    541. writeSheet();
    542. wb.write(fos);
    543. fos.flush();
    544. fos.close();
    545. return REPORT_PATH + fileName;
    546. } catch (Exception e) {
    547. log.error("导出Excel异常{}", e.getMessage());
    548. throw new UtilException("导出Excel失败,请联系网站管理员!");
    549. } finally {
    550. IOUtils.closeQuietly(wb);
    551. IOUtils.closeQuietly(fos);
    552. }
    553. }
    554. /**
    555. * 创建写入数据到Sheet
    556. */
    557. public void writeSheet() {
    558. // 取出一共有多少个sheet.
    559. int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
    560. for (int index = 0; index < sheetNo; index++) {
    561. createSheet(sheetNo, index);
    562. // 产生一行
    563. Row row = sheet.createRow(rowNum);
    564. int column = 0;
    565. // 写入各个字段的列头名称
    566. for (Object[] os : fields) {
    567. Excel excel = (Excel) os[1];
    568. this.createCell(excel, row, column++);
    569. }
    570. if (Type.EXPORT.equals(type)) {
    571. fillExcelData(index, row);
    572. addStatisticsRow();
    573. }
    574. }
    575. }
    576. /**
    577. * 填充excel数据
    578. *
    579. * @param index 序号
    580. * @param row 单元格行
    581. */
    582. public void fillExcelData(int index, Row row) {
    583. int startNo = index * sheetSize;
    584. int endNo = Math.min(startNo + sheetSize, list.size());
    585. for (int i = startNo; i < endNo; i++) {
    586. row = sheet.createRow(i + 1 + rowNum - startNo);
    587. // 得到导出对象.
    588. T vo = (T) list.get(i);
    589. int column = 0;
    590. for (Object[] os : fields) {
    591. Field field = (Field) os[0];
    592. Excel excel = (Excel) os[1];
    593. this.addCell(excel, row, vo, field, column++);
    594. }
    595. }
    596. }
    597. /**
    598. * 创建表格样式
    599. *
    600. * @param wb 工作薄对象
    601. * @return 样式列表
    602. */
    603. private Map<String, CellStyle> createStyles(Workbook wb) {
    604. // 写入各条记录,每条记录对应excel表中的一行
    605. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
    606. CellStyle style = wb.createCellStyle();
    607. style.setAlignment(HorizontalAlignment.CENTER);
    608. style.setVerticalAlignment(VerticalAlignment.CENTER);
    609. Font titleFont = wb.createFont();
    610. titleFont.setFontName("Arial");
    611. titleFont.setFontHeightInPoints((short) 16);
    612. titleFont.setBold(true);
    613. style.setFont(titleFont);
    614. styles.put("title", style);
    615. style = wb.createCellStyle();
    616. style.setAlignment(HorizontalAlignment.CENTER);
    617. style.setVerticalAlignment(VerticalAlignment.CENTER);
    618. style.setBorderRight(BorderStyle.THIN);
    619. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
    620. style.setBorderLeft(BorderStyle.THIN);
    621. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
    622. style.setBorderTop(BorderStyle.THIN);
    623. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
    624. style.setBorderBottom(BorderStyle.THIN);
    625. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
    626. Font dataFont = wb.createFont();
    627. dataFont.setFontName("Arial");
    628. dataFont.setFontHeightInPoints((short) 10);
    629. style.setFont(dataFont);
    630. styles.put("data", style);
    631. style = wb.createCellStyle();
    632. style.cloneStyleFrom(styles.get("data"));
    633. style.setAlignment(HorizontalAlignment.CENTER);
    634. style.setVerticalAlignment(VerticalAlignment.CENTER);
    635. style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
    636. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    637. Font headerFont = wb.createFont();
    638. headerFont.setFontName("Arial");
    639. headerFont.setFontHeightInPoints((short) 10);
    640. headerFont.setBold(true);
    641. headerFont.setColor(IndexedColors.WHITE.getIndex());
    642. style.setFont(headerFont);
    643. styles.put("header", style);
    644. style = wb.createCellStyle();
    645. style.setAlignment(HorizontalAlignment.CENTER);
    646. style.setVerticalAlignment(VerticalAlignment.CENTER);
    647. Font totalFont = wb.createFont();
    648. totalFont.setFontName("Arial");
    649. totalFont.setFontHeightInPoints((short) 10);
    650. style.setFont(totalFont);
    651. styles.put("total", style);
    652. style = wb.createCellStyle();
    653. style.cloneStyleFrom(styles.get("data"));
    654. style.setAlignment(HorizontalAlignment.LEFT);
    655. styles.put("data1", style);
    656. style = wb.createCellStyle();
    657. style.cloneStyleFrom(styles.get("data"));
    658. style.setAlignment(HorizontalAlignment.CENTER);
    659. styles.put("data2", style);
    660. style = wb.createCellStyle();
    661. style.cloneStyleFrom(styles.get("data"));
    662. style.setAlignment(HorizontalAlignment.RIGHT);
    663. styles.put("data3", style);
    664. return styles;
    665. }
    666. /**
    667. * 创建单元格
    668. */
    669. public Cell createCell(Excel attr, Row row, int column) {
    670. // 创建列
    671. Cell cell = row.createCell(column);
    672. // 写入列信息
    673. cell.setCellValue(attr.name());
    674. setDataValidation(attr, row, column);
    675. cell.setCellStyle(styles.get("header"));
    676. return cell;
    677. }
    678. /**
    679. * 设置单元格信息
    680. *
    681. * @param value 单元格值
    682. * @param attr 注解相关
    683. * @param cell 单元格信息
    684. */
    685. public void setCellVo(Object value, Excel attr, Cell cell) {
    686. if (ColumnType.STRING == attr.cellType()) {
    687. cell.setCellValue(ObjectUtil.isNull(value) ? attr.defaultValue() : value + attr.suffix());
    688. } else if (ColumnType.NUMERIC == attr.cellType()) {
    689. if (ObjectUtil.isNotNull(value)) {
    690. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
    691. }
    692. } else if (ColumnType.IMAGE == attr.cellType()) {
    693. ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
    694. String imagePath = Convert.toStr(value);
    695. if (StringUtils.isNotEmpty(imagePath)) {
    696. byte[] data = ImageUtils.getImage(imagePath);
    697. getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
    698. cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
    699. }
    700. }
    701. }
    702. /**
    703. * 获取图片类型,设置图片插入类型
    704. */
    705. public int getImageType(byte[] value) {
    706. String type = FileUtil.getSuffix(Arrays.toString(value));
    707. if ("JPG".equalsIgnoreCase(type)) {
    708. return Workbook.PICTURE_TYPE_JPEG;
    709. } else if ("PNG".equalsIgnoreCase(type)) {
    710. return Workbook.PICTURE_TYPE_PNG;
    711. }
    712. return Workbook.PICTURE_TYPE_JPEG;
    713. }
    714. /**
    715. * 创建表格样式
    716. */
    717. public void setDataValidation(Excel attr, Row row, int column) {
    718. if (attr.name().contains("注:")) {
    719. sheet.setColumnWidth(column, 6000);
    720. } else {
    721. // 设置列宽
    722. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
    723. }
    724. // 如果设置了提示信息则鼠标放上去提示.
    725. if (StringUtils.isNotEmpty(attr.prompt())) {
    726. // 这里默认设了2-101列提示.
    727. setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
    728. }
    729. // 如果设置了combo属性则本列只能选择不能输入
    730. if (attr.combo().length > 0) {
    731. // 这里默认设了2-101列只能选择不能输入.
    732. setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
    733. }
    734. }
    735. /**
    736. * 添加单元格
    737. */
    738. public Cell addCell(Excel attr, Row row, T vo, Field field, int column) {
    739. Cell cell = null;
    740. try {
    741. // 设置行高
    742. row.setHeight(maxHeight);
    743. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
    744. if (attr.isExport()) {
    745. // 创建cell
    746. cell = row.createCell(column);
    747. int align = attr.align().value();
    748. cell.setCellStyle(styles.get("data" + (align >= 1 && align <= 3 ? align : "")));
    749. // 用于读取对象中的属性
    750. Object value = getTargetValue(vo, field, attr);
    751. String dateFormat = attr.dateFormat();
    752. String readConverterExp = attr.readConverterExp();
    753. String separator = attr.separator();
    754. String dictType = attr.dictType();
    755. if (StringUtils.isNotEmpty(dateFormat) && ObjectUtil.isNotNull(value)) {
    756. cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
    757. } else if (StringUtils.isNotEmpty(readConverterExp) && ObjectUtil.isNotNull(value)) {
    758. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
    759. } else if (StringUtils.isNotEmpty(dictType) && ObjectUtil.isNotNull(value)) {
    760. cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
    761. } else if (value instanceof BigDecimal && -1 != attr.scale()) {
    762. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
    763. } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) {
    764. cell.setCellValue(dataFormatHandlerAdapter(value, attr));
    765. } else {
    766. // 设置列类型
    767. setCellVo(value, attr, cell);
    768. }
    769. addStatisticsData(column, Convert.toStr(value), attr);
    770. }
    771. } catch (Exception e) {
    772. log.error("导出Excel失败{}", e.getMessage());
    773. }
    774. return cell;
    775. }
    776. /**
    777. * 设置 POI XSSFSheet 单元格提示
    778. *
    779. * @param sheet 表单
    780. * @param promptTitle 提示标题
    781. * @param promptContent 提示内容
    782. * @param firstRow 开始行
    783. * @param endRow 结束行
    784. * @param firstCol 开始列
    785. * @param endCol 结束列
    786. */
    787. public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
    788. int firstCol, int endCol) {
    789. DataValidationHelper helper = sheet.getDataValidationHelper();
    790. DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
    791. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
    792. DataValidation dataValidation = helper.createValidation(constraint, regions);
    793. dataValidation.createPromptBox(promptTitle, promptContent);
    794. dataValidation.setShowPromptBox(true);
    795. sheet.addValidationData(dataValidation);
    796. }
    797. /**
    798. * 设置某些列的值只能输入预制的数据,显示下拉框.
    799. *
    800. * @param sheet 要设置的sheet.
    801. * @param textlist 下拉框显示的内容
    802. * @param firstRow 开始行
    803. * @param endRow 结束行
    804. * @param firstCol 开始列
    805. * @param endCol 结束列
    806. */
    807. public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
    808. DataValidationHelper helper = sheet.getDataValidationHelper();
    809. // 加载下拉列表内容
    810. DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
    811. // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
    812. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
    813. // 数据有效性对象
    814. DataValidation dataValidation = helper.createValidation(constraint, regions);
    815. // 处理Excel兼容性问题
    816. if (dataValidation instanceof XSSFDataValidation) {
    817. dataValidation.setSuppressDropDownArrow(true);
    818. dataValidation.setShowErrorBox(true);
    819. } else {
    820. dataValidation.setSuppressDropDownArrow(false);
    821. }
    822. sheet.addValidationData(dataValidation);
    823. }
    824. /**
    825. * 数据处理器
    826. *
    827. * @param value 数据值
    828. * @param excel 数据注解
    829. * @return
    830. */
    831. public String dataFormatHandlerAdapter(Object value, Excel excel) {
    832. try {
    833. Object instance = excel.handler().newInstance();
    834. Method formatMethod = excel.handler().getMethod("format", new Class[]{Object.class, String[].class});
    835. value = formatMethod.invoke(instance, value, excel.args());
    836. } catch (Exception e) {
    837. log.error("不能格式化数据 " + excel.handler(), e.getMessage());
    838. }
    839. return Convert.toStr(value);
    840. }
    841. /**
    842. * 合计统计信息
    843. */
    844. private void addStatisticsData(Integer index, String text, Excel entity) {
    845. if (entity != null && entity.isStatistics()) {
    846. Double temp = 0D;
    847. if (!statistics.containsKey(index)) {
    848. statistics.put(index, temp);
    849. }
    850. try {
    851. temp = Double.valueOf(text);
    852. } catch (NumberFormatException e) {
    853. }
    854. statistics.put(index, statistics.get(index) + temp);
    855. }
    856. }
    857. /**
    858. * 创建统计行
    859. */
    860. public void addStatisticsRow() {
    861. if (statistics.size() > 0) {
    862. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
    863. Set<Integer> keys = statistics.keySet();
    864. Cell cell = row.createCell(0);
    865. cell.setCellStyle(styles.get("total"));
    866. cell.setCellValue("合计");
    867. for (Integer key : keys) {
    868. cell = row.createCell(key);
    869. cell.setCellStyle(styles.get("total"));
    870. cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
    871. }
    872. statistics.clear();
    873. }
    874. }
    875. /**
    876. * 编码文件名
    877. */
    878. public String encodingFilename(String filename) {
    879. filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
    880. return filename;
    881. }
    882. /**
    883. * 获取下载路径
    884. *
    885. * @param filename 文件名称
    886. */
    887. public String getAbsoluteFile(String filename) {
    888. String downloadPath = ProjectConfig.getDownloadPath() + filename;
    889. File desc = new File(downloadPath);
    890. if (!desc.getParentFile().exists()) {
    891. desc.getParentFile().mkdirs();
    892. }
    893. return downloadPath;
    894. }
    895. /**
    896. * 获取bean中的属性值
    897. *
    898. * @param vo 实体对象
    899. * @param field 字段
    900. * @param excel 注解
    901. * @return 最终的属性值
    902. * @throws Exception
    903. */
    904. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
    905. Object o = field.get(vo);
    906. if (StringUtils.isNotEmpty(excel.targetAttr())) {
    907. String target = excel.targetAttr();
    908. if (target.indexOf(".") > -1) {
    909. String[] targets = target.split("[.]");
    910. for (String name : targets) {
    911. o = getValue(o, name);
    912. }
    913. } else {
    914. o = getValue(o, target);
    915. }
    916. }
    917. return o;
    918. }
    919. /**
    920. * 以类的属性的get方法方法形式获取值
    921. *
    922. * @param o
    923. * @param name
    924. * @return value
    925. * @throws Exception
    926. */
    927. private Object getValue(Object o, String name) throws Exception {
    928. if (ObjectUtil.isNotNull(o) && StringUtils.isNotEmpty(name)) {
    929. Class<?> clazz = o.getClass();
    930. Field field = clazz.getDeclaredField(name);
    931. field.setAccessible(true);
    932. o = field.get(o);
    933. }
    934. return o;
    935. }
    936. /**
    937. * 得到所有定义字段
    938. */
    939. private void createExcelField() {
    940. this.fields = getFields();
    941. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
    942. this.maxHeight = getRowHeight();
    943. }
    944. /**
    945. * 获取字段注解信息
    946. */
    947. public List<Object[]> getFields() {
    948. List<Object[]> fields = new ArrayList<Object[]>();
    949. List<Field> tempFields = new ArrayList<>();
    950. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
    951. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
    952. for (Field field : tempFields) {
    953. // 单注解
    954. if (field.isAnnotationPresent(Excel.class)) {
    955. Excel attr = field.getAnnotation(Excel.class);
    956. if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
    957. field.setAccessible(true);
    958. fields.add(new Object[]{field, attr});
    959. }
    960. }
    961. // 多注解
    962. if (field.isAnnotationPresent(Excels.class)) {
    963. Excels attrs = field.getAnnotation(Excels.class);
    964. Excel[] excels = attrs.value();
    965. for (Excel attr : excels) {
    966. if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
    967. field.setAccessible(true);
    968. fields.add(new Object[]{field, attr});
    969. }
    970. }
    971. }
    972. }
    973. return fields;
    974. }
    975. /**
    976. * 根据注解获取最大行高
    977. */
    978. public short getRowHeight() {
    979. double maxHeight = 0;
    980. for (Object[] os : this.fields) {
    981. Excel excel = (Excel) os[1];
    982. maxHeight = maxHeight > excel.height() ? maxHeight : excel.height();
    983. }
    984. return (short) (maxHeight * 20);
    985. }
    986. /**
    987. * 创建一个工作簿
    988. */
    989. public void createWorkbook() {
    990. this.wb = new SXSSFWorkbook(500);
    991. this.sheet = wb.createSheet();
    992. wb.setSheetName(0, sheetName);
    993. this.styles = createStyles(wb);
    994. }
    995. /**
    996. * 创建工作表
    997. *
    998. * @param sheetNo sheet数量
    999. * @param index 序号
    1000. */
    1001. public void createSheet(int sheetNo, int index) {
    1002. // 设置工作表的名称.
    1003. if (sheetNo > 1 && index > 0) {
    1004. this.sheet = wb.createSheet();
    1005. this.createTitle();
    1006. String tempName = index + "_" + sheetName;
    1007. log.info("sheet{}:{}", index, tempName);
    1008. wb.setSheetName(index, tempName);
    1009. }
    1010. }
    1011. /**
    1012. * 获取单元格值
    1013. *
    1014. * @param row 获取的行
    1015. * @param column 获取单元格列号
    1016. * @return 单元格值
    1017. */
    1018. public Object getCellValue(Row row, int column) {
    1019. if (row == null) {
    1020. return row;
    1021. }
    1022. Object val = "";
    1023. try {
    1024. Cell cell = row.getCell(column);
    1025. if (ObjectUtil.isNotNull(cell)) {
    1026. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) {
    1027. val = cell.getNumericCellValue();
    1028. if (DateUtil.isCellDateFormatted(cell)) {
    1029. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
    1030. } else {
    1031. if ((Double) val % 1 != 0) {
    1032. val = new BigDecimal(val.toString());
    1033. } else {
    1034. val = new DecimalFormat("0").format(val);
    1035. }
    1036. }
    1037. } else if (cell.getCellType() == CellType.STRING) {
    1038. val = cell.getStringCellValue();
    1039. } else if (cell.getCellType() == CellType.BOOLEAN) {
    1040. val = cell.getBooleanCellValue();
    1041. } else if (cell.getCellType() == CellType.ERROR) {
    1042. val = cell.getErrorCellValue();
    1043. }
    1044. }
    1045. } catch (Exception e) {
    1046. return val;
    1047. }
    1048. return val;
    1049. }
    1050. /**
    1051. * 判断是否是空行
    1052. *
    1053. * @param row 判断的行
    1054. * @return
    1055. */
    1056. private boolean isRowEmpty(Row row) {
    1057. if (row == null) {
    1058. return true;
    1059. }
    1060. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
    1061. Cell cell = row.getCell(i);
    1062. if (cell != null && cell.getCellType() != CellType.BLANK) {
    1063. return false;
    1064. }
    1065. }
    1066. return true;
    1067. }
    1068. public static void exportToExcelFile(String excelPath,String fileName,Map<String, String> headerMapping,List<Map<String,Object>> dataList, boolean isWriteHeader) throws IOException {
    1069. try {
    1070. excelPath = excelPath+ File.separator+fileName;
    1071. File file = new File(excelPath);
    1072. //创建一个工作薄
    1073. Workbook workbook = new SXSSFWorkbook(5000);
    1074. if (workbook != null) {
    1075. //生成一个表格
    1076. Sheet sheet = workbook.createSheet();
    1077. List<String> headers = new ArrayList<String>();
    1078. List<String> fields = new ArrayList<String>();
    1079. for(Map.Entry<String,String> strKey : headerMapping.entrySet()) {
    1080. fields.add(strKey.getKey());
    1081. headers.add(strKey.getValue());
    1082. }
    1083. //生成表格标题行
    1084. if(isWriteHeader) {
    1085. Row row = sheet.createRow(0);
    1086. for (int i = 0; i < headers.size(); i++) {
    1087. Cell cell = row.createCell(i);
    1088. cell.setCellValue(headers.get(i));
    1089. }
    1090. }
    1091. //生成数据部分
    1092. if(dataList != null && dataList.size()>0){
    1093. int index = 0;
    1094. if(isWriteHeader) {
    1095. index = 0;
    1096. } else {
    1097. index = -1;
    1098. }
    1099. for(Map<String, Object> record : dataList){
    1100. index++;
    1101. Row newRow = sheet.createRow(index);
    1102. for (int i = 0; i < fields.size(); i++) {
    1103. Object value = record.get(fields.get(i).toLowerCase());
    1104. Cell cell = newRow.createCell(i);
    1105. if (value == null) {
    1106. cell.setCellValue("");
    1107. } else {
    1108. cell.setCellValue(String.valueOf(value));
    1109. }
    1110. }
    1111. }
    1112. }
    1113. }
    1114. //创建文件流
    1115. OutputStream stream = new FileOutputStream(excelPath);
    1116. //写入数据
    1117. workbook.write(stream);
    1118. //关闭文件流
    1119. stream.close();
    1120. } catch (IOException e) {
    1121. e.printStackTrace();
    1122. }
    1123. }
    1124. }

    可以运用于实战中的工具类