easyexcel导出

x33g5p2x  于2022-05-18 转载在 其他  
字(8.5k)|赞(0)|评价(0)|浏览(815)

easyexcel导出

一、依赖

  1. <!--阿里巴巴EasyExcel依赖-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>easyexcel</artifactId>
  5. <version>2.2.10</version>
  6. </dependency>

参考文档:语雀easyexcel文档

二、导出

普通导出

  1. /**
  2. * 导出
  3. *
  4. * @param response 响应流
  5. * @param fileName 文件名称
  6. * @param list 数据
  7. * @param clazz class文件
  8. */
  9. public static void exportExcel(HttpServletResponse response, String fileName, String sheetName, List<?> list, Class<?> clazz) {
  10. if (CollectionUtils.isEmpty(list)) {
  11. throw new RuntimeException();
  12. }
  13. if (StringUtils.isEmpty(fileName)) {
  14. fileName = new Date().toString();
  15. }
  16. try {
  17. response.setContentType("application/vnd.ms-excel");
  18. response.setCharacterEncoding("utf-8");
  19. // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
  20. try {
  21. fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
  22. } catch (UnsupportedEncodingException e) {
  23. e.printStackTrace();
  24. }
  25. response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
  26. EasyExcel.write(response.getOutputStream(), clazz)
  27. // 导出文件名
  28. .autoCloseStream(Boolean.TRUE).sheet(sheetName)
  29. .doWrite(list);
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. }
  33. }

实体类

  1. @HeadRowHeight
  2. @HeadStyle(horizontalAlignment = CENTER)
  3. public class ExportAssetModel {
  4. @ColumnWidth(30)
  5. @HeadStyle(fillForegroundColor = 40)
  6. @ContentStyle(wrapped = true)
  7. @ExcelProperty({"基础属性", "制造商\n(可输入数字0-9字母a-zA-Z,下划线_-以及汉字,最大长字符64位)\n(必填)"})
  8. private String manufacturer;
  9. @ColumnWidth(30)
  10. @HeadStyle(fillForegroundColor = 40)
  11. @ContentStyle(wrapped = true)
  12. @ExcelProperty({"基础属性", "型号\n(请输入1-64个字符,可输入中文,数字0-9,字母a-zA-Z,空格,以及字符+._-()()[]:,/)\n(必填)"})
  13. private String model;
  14. @ColumnWidth(30)
  15. @HeadStyle(fillForegroundColor = 40)
  16. @ContentStyle(wrapped = true)
  17. @ExcelProperty({"基础属性", "设备类型\n(请输入1-64个字符,只能输入中文,英文,数字,空格和特殊字符#@_.*-/[]()~′^{}|:;、,‘’)\n(必填)"})
  18. private String deviceTypeStr;
  19. @ColumnWidth(30)
  20. @HeadStyle(fillForegroundColor = 40)
  21. @ContentStyle(wrapped = true)
  22. @ExcelProperty({"基础属性", "状态\n(只能输入使用中、未使用)"})
  23. private String status;
  24. @ColumnWidth(30)
  25. @HeadStyle(fillForegroundColor = 40)
  26. @ContentStyle(wrapped = true)
  27. @ExcelProperty({"基础属性", "备注\n(请输入1-64个字符,只能输入中文,英文,数字,空格和特殊字符#@_.*-/[]()~′^{}|:;、,‘’)"})
  28. private String remark;
  29. @ColumnWidth(30)
  30. @HeadStyle(fillForegroundColor = 53)
  31. @ContentStyle(wrapped = true)
  32. @ExcelProperty({"扩展属性", "高度(U)\n(请输入1-100之间的整数)\n(IT设备、通信设备必填)"})
  33. private String height;
  34. @ColumnWidth(30)
  35. @HeadStyle(fillForegroundColor = 53)
  36. @ContentStyle(wrapped = true)
  37. @ExcelProperty({"扩展属性", "重量(Kg)\n(请输入0-9999.99之间的数)"})
  38. private String weight;
  39. @ColumnWidth(30)
  40. @HeadStyle(fillForegroundColor = 53)
  41. @ContentStyle(wrapped = true)
  42. @ExcelProperty({"扩展属性", "额定功率(W)\n(请输入0-9999999.99之间的数)\n(IT设备、通信设备必填)"})
  43. private String ratedPower;
  44. @ColumnWidth(30)
  45. @HeadStyle(fillForegroundColor = 53)
  46. @ContentStyle(wrapped = true)
  47. @ExcelProperty({"扩展属性", "配电端口数\n(请输入0-2048之间的整数)"})
  48. private String distributionPort;
  49. @ColumnWidth(30)
  50. @HeadStyle(fillForegroundColor = 53)
  51. @ContentStyle(wrapped = true)
  52. @ExcelProperty({"扩展属性", "网络端口数\n(请输入0-2048之间的整数)"})
  53. private String networkPort;
  54. }

导出效果

自定义表头导出

  1. /**
  2. * 自定义表头导出
  3. *
  4. * @param response
  5. * @param fileName
  6. * @param sheetName
  7. * @param list
  8. * @param head
  9. */
  10. public static void customHeadExportExcel(HttpServletResponse response, String fileName, String sheetName, List<List<Object>> list, List<List<String>> head) {
  11. if (CollectionUtils.isEmpty(list)) {
  12. throw new RuntimeException();
  13. }
  14. if (CollectionUtils.isEmpty(head)) {
  15. throw new RuntimeException();
  16. }
  17. if (StringUtils.isEmpty(fileName)) {
  18. fileName = new Date().toString();
  19. }
  20. try {
  21. response.setContentType("application/vnd.ms-excel");
  22. response.setCharacterEncoding("utf-8");
  23. // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
  24. try {
  25. fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
  26. } catch (UnsupportedEncodingException e) {
  27. e.printStackTrace();
  28. }
  29. response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
  30. EasyExcel.write(response.getOutputStream())
  31. .head(head)
  32. //默认策略
  33. // .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
  34. .registerWriteHandler(myHorizontalCellStyleStrategy())
  35. .registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))//简单的列宽策略,列宽20
  36. // .registerWriteHandler(new SimpleRowHeightStyleStrategy((short)25,(short)25))//简单的行高策略
  37. // 导出文件名
  38. .autoCloseStream(Boolean.TRUE)
  39. .sheet(sheetName)
  40. .doWrite(list);
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. private static HorizontalCellStyleStrategy myHorizontalCellStyleStrategy() {
  46. //1 表头样式策略
  47. WriteCellStyle headWriteCellStyle = new WriteCellStyle();
  48. //设置表头居中对齐
  49. headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
  50. //表头前景设置淡蓝色
  51. headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
  52. WriteFont headWriteFont = new WriteFont();
  53. headWriteFont.setBold(true);
  54. headWriteFont.setFontName("宋体");
  55. headWriteFont.setFontHeightInPoints((short) 12);
  56. headWriteCellStyle.setWriteFont(headWriteFont);
  57. //内容样式 多个样式则隔行换色
  58. List<WriteCellStyle> listCntWritCellSty = new ArrayList<>();
  59. //2 内容样式策略 样式一
  60. WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
  61. WriteFont contentWriteFont = new WriteFont();
  62. //内容字体大小
  63. contentWriteFont.setFontName("宋体");
  64. contentWriteFont.setFontHeightInPoints((short) 11);
  65. contentWriteCellStyle.setWriteFont(contentWriteFont);
  66. //设置自动换行
  67. contentWriteCellStyle.setWrapped(true);
  68. //设置垂直居中
  69. contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  70. // 头默认了 FillPatternType所以可以不指定。
  71. contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
  72. //设置背景黄色
  73. contentWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
  74. //设置水平靠左
  75. contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
  76. //设置边框样式
  77. setBorderStyle(contentWriteCellStyle);
  78. //内容风格可以定义多个。
  79. listCntWritCellSty.add(contentWriteCellStyle);
  80. //2 内容样式策略 样式二
  81. WriteCellStyle contentWriteCellStyle2 = new WriteCellStyle();
  82. // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色。
  83. // 头默认了 FillPatternType所以可以不指定。
  84. contentWriteCellStyle2.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
  85. // 背景绿色
  86. contentWriteCellStyle2.setFillForegroundColor(IndexedColors.GREEN.getIndex());
  87. //设置垂直居中
  88. contentWriteCellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);
  89. contentWriteCellStyle2.setHorizontalAlignment(HorizontalAlignment.LEFT);
  90. //设置边框样式
  91. setBorderStyle(contentWriteCellStyle2);
  92. listCntWritCellSty.add(contentWriteCellStyle2);
  93. // 水平单元格风格综合策略(表头 + 内容)
  94. // return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
  95. return new HorizontalCellStyleStrategy(headWriteCellStyle, listCntWritCellSty);
  96. }
  97. /**
  98. * 设置边框样式
  99. *
  100. * @param contentWriteCellStyle
  101. */
  102. private static void setBorderStyle(WriteCellStyle contentWriteCellStyle) {
  103. //设置边框样式
  104. contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
  105. // contentWriteCellStyle.setBottomBorderColor(IndexedColors.BLUE.getIndex()); //颜色
  106. contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
  107. contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
  108. contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
  109. }

多sheet导出

  1. public static void exportMoreExcel(HttpServletResponse response, String fileName,
  2. String sheetNameOne,String sheetNameTwo,String sheetNameThree,
  3. List<List<Object>> list, List<List<String>> head,
  4. List<?> listTwo,Class<?> clazzTwo, List<?> listThree,Class<?> clazzThree) {
  5. if (CollectionUtils.isEmpty(list)) {
  6. throw new RuntimeException();
  7. }
  8. if (CollectionUtils.isEmpty(head)) {
  9. throw new RuntimeException();
  10. }
  11. if (StringUtils.isEmpty(fileName)) {
  12. fileName = new Date().toString();
  13. }
  14. try {
  15. response.setContentType("application/vnd.ms-excel");
  16. response.setCharacterEncoding("utf-8");
  17. // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
  18. try {
  19. fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
  20. } catch (UnsupportedEncodingException e) {
  21. e.printStackTrace();
  22. }
  23. response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
  24. ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
  25. WriteSheet writeSheet = EasyExcel.writerSheet(1, sheetNameOne)
  26. .head(head)
  27. .registerWriteHandler(myHorizontalCellStyleStrategy())
  28. .registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))//简单的列宽策略,列宽20
  29. .build();
  30. excelWriter.write(list, writeSheet);
  31. writeSheet = EasyExcel.writerSheet(2, sheetNameTwo).head(clazzTwo).build();
  32. excelWriter.write(listTwo, writeSheet);
  33. writeSheet = EasyExcel.writerSheet(3, sheetNameThree).head(clazzThree).build();
  34. excelWriter.write(listThree, writeSheet);
  35. // 千万别忘记finish 会帮忙关闭流
  36. excelWriter.finish();
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. }

创作打卡挑战赛

赢取流量/现金/CSDN周边激励大奖

相关文章