EasyExcelUtil.java 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. package com.inspur.customer.utils;
  2. import com.alibaba.excel.EasyExcelFactory;
  3. import com.alibaba.excel.annotation.ExcelProperty;
  4. import com.alibaba.excel.support.ExcelTypeEnum;
  5. import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
  6. import com.alibaba.excel.write.handler.WriteHandler;
  7. import com.alibaba.excel.write.metadata.style.WriteCellStyle;
  8. import com.alibaba.excel.write.metadata.style.WriteFont;
  9. import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
  10. import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
  11. import com.google.common.collect.Lists;
  12. import org.apache.poi.ss.usermodel.BorderStyle;
  13. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  14. import org.apache.poi.ss.usermodel.IndexedColors;
  15. import org.apache.poi.ss.usermodel.VerticalAlignment;
  16. import org.springframework.core.annotation.AnnotationUtils;
  17. import org.springframework.util.ReflectionUtils;
  18. import javax.servlet.http.HttpServletResponse;
  19. import java.io.IOException;
  20. import java.io.OutputStream;
  21. import java.lang.reflect.Field;
  22. import java.net.URLEncoder;
  23. import java.time.LocalDateTime;
  24. import java.time.format.DateTimeFormatter;
  25. import java.util.ArrayList;
  26. import java.util.Comparator;
  27. import java.util.List;
  28. /**
  29. * @author zengweijie
  30. * @version 1.0
  31. * @date 2022/12/12
  32. **/
  33. public class EasyExcelUtil {
  34. /**
  35. * 导出 Excel :一个 sheet,带表头.
  36. *
  37. * @param response HttpServletResponse
  38. * @param data 数据 list,每个元素为一个 BaseRowModel
  39. * @param fileName 导出的文件名
  40. * @param sheetName 导入文件的 sheet 名
  41. * @param model 映射实体类,Excel 模型
  42. * @throws Exception 异常
  43. */
  44. public static void writeExcel(HttpServletResponse response, List<? extends Object> data, String fileName, String sheetName, Class<?> model, boolean putExportTimeToHead) throws Exception {
  45. writeExcel(response, data, fileName, sheetName, model, null, putExportTimeToHead);
  46. }
  47. public static void writeExcel(HttpServletResponse response, List<? extends Object> data, String fileName, String sheetName, Class<?> model, List<WriteHandler> writeHandlerList, boolean putExportTimeToHead) throws Exception {
  48. // 头的策略
  49. WriteCellStyle headWriteCellStyle = new WriteCellStyle();
  50. //设置表头居中对齐
  51. headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
  52. // 颜色
  53. headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
  54. WriteFont headWriteFont = new WriteFont();
  55. headWriteFont.setFontHeightInPoints((short) 16);
  56. // 字体
  57. headWriteCellStyle.setWriteFont(headWriteFont);
  58. headWriteCellStyle.setWrapped(true);
  59. // 内容的策略
  60. WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
  61. WriteFont contentWriteFont = new WriteFont();
  62. contentWriteFont.setFontHeightInPoints((short) 12);
  63. contentWriteCellStyle.setWriteFont(contentWriteFont);
  64. //设置内容靠中对齐
  65. contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
  66. contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  67. contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
  68. contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
  69. contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
  70. contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
  71. // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
  72. HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
  73. try (OutputStream outputStream = getOutputStream(fileName, response)) {
  74. ExcelWriterSheetBuilder excelWriterSheetBuilder = EasyExcelFactory.write(outputStream, model).excelType(ExcelTypeEnum.XLSX).sheet(sheetName);
  75. if (writeHandlerList != null && !writeHandlerList.isEmpty()) {
  76. for (WriteHandler writeHandler : writeHandlerList) {
  77. excelWriterSheetBuilder.registerWriteHandler(writeHandler);
  78. }
  79. }
  80. if (putExportTimeToHead) {
  81. excelWriterSheetBuilder.head(getHeadWithExportTime(model));
  82. }
  83. excelWriterSheetBuilder.registerWriteHandler(horizontalCellStyleStrategy).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).doWrite(data);
  84. }
  85. }
  86. public static void writeExcel(HttpServletResponse response, List<? extends Object> data, String fileName, String sheetName, List<List<String>> head, List<WriteHandler> writeHandlerList, boolean putExportTimeToHead) throws Exception {
  87. // 头的策略
  88. WriteCellStyle headWriteCellStyle = new WriteCellStyle();
  89. //设置表头居中对齐
  90. headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
  91. // 颜色
  92. headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
  93. WriteFont headWriteFont = new WriteFont();
  94. headWriteFont.setFontHeightInPoints((short) 16);
  95. // 字体
  96. headWriteCellStyle.setWriteFont(headWriteFont);
  97. headWriteCellStyle.setWrapped(true);
  98. // 内容的策略
  99. WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
  100. WriteFont contentWriteFont = new WriteFont();
  101. contentWriteFont.setFontHeightInPoints((short) 12);
  102. contentWriteCellStyle.setWriteFont(contentWriteFont);
  103. //设置内容靠中对齐
  104. contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
  105. contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  106. contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
  107. contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
  108. contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
  109. contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
  110. // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
  111. HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
  112. try (OutputStream outputStream = getOutputStream(fileName, response)) {
  113. ExcelWriterSheetBuilder excelWriterSheetBuilder = EasyExcelFactory.write(outputStream).excelType(ExcelTypeEnum.XLSX).sheet(sheetName);
  114. if (writeHandlerList != null && !writeHandlerList.isEmpty()) {
  115. for (WriteHandler writeHandler : writeHandlerList) {
  116. excelWriterSheetBuilder.registerWriteHandler(writeHandler);
  117. }
  118. }
  119. if (putExportTimeToHead) {
  120. excelWriterSheetBuilder.head(getHeadWithExportTime(head));
  121. }
  122. excelWriterSheetBuilder.registerWriteHandler(horizontalCellStyleStrategy).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).doWrite(data);
  123. }
  124. }
  125. /**
  126. * 导出文件时为Writer生成OutputStream.
  127. *
  128. * @param fileName 文件名
  129. * @param response response
  130. * @return ""
  131. */
  132. private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
  133. try {
  134. fileName = URLEncoder.encode(fileName, "UTF-8");
  135. response.setContentType("application/vnd.ms-excel;charset=utf-8");
  136. response.setCharacterEncoding("utf8");
  137. response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
  138. response.setHeader("Pragma", "public");
  139. response.setHeader("Cache-Control", "no-store");
  140. response.addHeader("Cache-Control", "max-age=0");
  141. return response.getOutputStream();
  142. } catch (IOException e) {
  143. throw new Exception("导出excel表格失败!", e);
  144. }
  145. }
  146. private static List<List<String>> getHeadWithExportTime(Class<?> clazz) {
  147. List<List<String>> head = new ArrayList<>();
  148. List<Field> fieldList = new ArrayList<>();
  149. ReflectionUtils.doWithFields(clazz, fieldList::add);
  150. List<ExcelProperty> annotationList = new ArrayList<>();
  151. for (Field field : fieldList) {
  152. ExcelProperty annotation = AnnotationUtils.getAnnotation(field, ExcelProperty.class);
  153. if (annotation != null) {
  154. annotationList.add(annotation);
  155. }
  156. }
  157. annotationList.sort(Comparator.comparing(ExcelProperty::index));
  158. for (ExcelProperty excelProperty : annotationList) {
  159. head.add(Lists.newArrayList(excelProperty.value()));
  160. }
  161. String top = String.format("导出时间:%s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
  162. for (List<String> strings : head) {
  163. strings.add(0, top);
  164. }
  165. return head;
  166. }
  167. private static List<List<String>> getHeadWithExportTime(List<List<String>> head) {
  168. String top = String.format("导出时间:%s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
  169. for (List<String> strings : head) {
  170. strings.add(0, top);
  171. }
  172. return head;
  173. }
  174. }