当前位置:   article > 正文

easyExcel 导出文件时,设置单元格样式,自适应列宽_writecellstyle设置宽度

writecellstyle设置宽度

目录

1、自适应列宽实现类

2、单元格样式实现类

3、导出的时候,特殊数据类型,需要设置转换类,不然注解导出方式会报错

        注解使用方式

        日期转换类

4、web导出excel(将excel数据写入到response输出流中)



本博客不是写给小白的,小白可以去官网看案例: 写Excel | Easy Excel

基于easyExcel 3.2.0 版本


1、自适应列宽实现类

  1. package com.xinba.statistical.rules.base.utils.excel;
  2. import com.alibaba.excel.enums.CellDataTypeEnum;
  3. import com.alibaba.excel.metadata.CellData;
  4. import com.alibaba.excel.metadata.Head;
  5. import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
  6. import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
  7. import org.apache.commons.collections4.CollectionUtils;
  8. import org.apache.poi.ss.usermodel.Cell;
  9. import java.util.HashMap;
  10. import java.util.List;
  11. import java.util.Map;
  12. public class ExcelCellWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
  13. // 可以根据这里的最大宽度,按自己需要进行调整,搭配单元格样式实现类中的,自动换行,效果更好
  14. private static final int MAX_COLUMN_WIDTH = 50;
  15. private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap(8);
  16. @Override
  17. protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
  18. boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
  19. if (needSetWidth) {
  20. Map<Integer, Integer> maxColumnWidthMap = (Map)CACHE.get(writeSheetHolder.getSheetNo());
  21. if (maxColumnWidthMap == null) {
  22. maxColumnWidthMap = new HashMap(16);
  23. CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
  24. }
  25. Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
  26. if (columnWidth >= 0) {
  27. if (columnWidth > MAX_COLUMN_WIDTH) {
  28. columnWidth = MAX_COLUMN_WIDTH;
  29. }
  30. Integer maxColumnWidth = (Integer)((Map)maxColumnWidthMap).get(cell.getColumnIndex());
  31. if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
  32. ((Map)maxColumnWidthMap).put(cell.getColumnIndex(), columnWidth);
  33. writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
  34. }
  35. }
  36. }
  37. }
  38. private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
  39. if (isHead) {
  40. return cell.getStringCellValue().getBytes().length;
  41. } else {
  42. CellData cellData = (CellData)cellDataList.get(0);
  43. CellDataTypeEnum type = cellData.getType();
  44. if (type == null) {
  45. return -1;
  46. } else {
  47. switch(type) {
  48. case STRING:
  49. return cellData.getStringValue().getBytes().length;
  50. case BOOLEAN:
  51. return cellData.getBooleanValue().toString().getBytes().length;
  52. case NUMBER:
  53. return cellData.getNumberValue().toString().getBytes().length;
  54. default:
  55. return -1;
  56. }
  57. }
  58. }
  59. }
  60. }

2、单元格样式实现类

  1. package com.xinba.statistical.rules.base.utils.excel;
  2. import com.alibaba.excel.write.metadata.style.WriteCellStyle;
  3. import com.alibaba.excel.write.metadata.style.WriteFont;
  4. import org.apache.poi.ss.usermodel.BorderStyle;
  5. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  6. import org.apache.poi.ss.usermodel.VerticalAlignment;
  7. public class StyleUtils {
  8. private static final String[] _formats = new String[]{
  9. "General",
  10. "0",
  11. "0.00",
  12. "#,##0",
  13. "#,##0.00",
  14. "\"$\"#,##0_);(\"$\"#,##0)",
  15. "\"$\"#,##0_);[Red](\"$\"#,##0)",
  16. "\"$\"#,##0.00_);(\"$\"#,##0.00)",
  17. "\"$\"#,##0.00_);[Red](\"$\"#,##0.00)",
  18. "0%", "0.00%", "0.00E+00",
  19. "# ?/?", "# ??/??",
  20. "m/d/yy", "d-mmm-yy",
  21. "d-mmm", "mmm-yy",
  22. "h:mm AM/PM",
  23. "h:mm:ss AM/PM",
  24. "h:mm", "h:mm:ss",
  25. "m/d/yy h:mm",
  26. "reserved-0x17",
  27. "reserved-0x18",
  28. "reserved-0x19",
  29. "reserved-0x1A",
  30. "reserved-0x1B",
  31. "reserved-0x1C",
  32. "reserved-0x1D",
  33. "reserved-0x1E",
  34. "reserved-0x1F",
  35. "reserved-0x20",
  36. "reserved-0x21",
  37. "reserved-0x22",
  38. "reserved-0x23",
  39. "reserved-0x24",
  40. "#,##0_);(#,##0)",
  41. "#,##0_);[Red](#,##0)",
  42. "#,##0.00_);(#,##0.00)",
  43. "#,##0.00_);[Red](#,##0.00)",
  44. "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)",
  45. "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)",
  46. "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)",
  47. "_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)",
  48. "mm:ss",
  49. "[h]:mm:ss",
  50. "mm:ss.0",
  51. "##0.0E+0",
  52. "@" // 文本格式
  53. };
  54. /**
  55. * 标题样式
  56. * @return
  57. */
  58. public static WriteCellStyle getHeadStyle(){
  59. // 头的策略
  60. WriteCellStyle headWriteCellStyle = new WriteCellStyle();
  61. // 背景颜色
  62. // headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE1.getIndex());
  63. // headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
  64. // 字体
  65. WriteFont headWriteFont = new WriteFont();
  66. headWriteFont.setFontName("宋体");//设置字体名字
  67. headWriteFont.setFontHeightInPoints((short)10);//设置字体大小
  68. headWriteFont.setBold(true);//字体加粗
  69. headWriteCellStyle.setWriteFont(headWriteFont); //在样式用应用设置的字体;
  70. // 样式
  71. headWriteCellStyle.setBorderBottom(BorderStyle.THIN);//设置底边框;
  72. headWriteCellStyle.setBottomBorderColor((short) 0);//设置底边框颜色;
  73. headWriteCellStyle.setBorderLeft(BorderStyle.THIN); //设置左边框;
  74. headWriteCellStyle.setLeftBorderColor((short) 0);//设置左边框颜色;
  75. headWriteCellStyle.setBorderRight(BorderStyle.THIN);//设置右边框;
  76. headWriteCellStyle.setRightBorderColor((short) 0);//设置右边框颜色;
  77. headWriteCellStyle.setBorderTop(BorderStyle.THIN);//设置顶边框;
  78. headWriteCellStyle.setTopBorderColor((short) 0); //设置顶边框颜色;
  79. headWriteCellStyle.setWrapped(true); //设置自动换行;
  80. headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);//设置水平对齐的样式为居中对齐;
  81. headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //设置垂直对齐的样式为居中对齐;
  82. headWriteCellStyle.setShrinkToFit(true);//设置文本收缩至合适
  83. return headWriteCellStyle;
  84. }
  85. /**
  86. * 内容样式
  87. * @return
  88. */
  89. public static WriteCellStyle getContentStyle(){
  90. // 内容的策略
  91. WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
  92. // 背景绿色
  93. // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
  94. // contentWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
  95. // contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
  96. // 设置字体
  97. WriteFont contentWriteFont = new WriteFont();
  98. contentWriteFont.setFontHeightInPoints((short) 9);//设置字体大小
  99. contentWriteFont.setFontName("宋体"); //设置字体名字
  100. contentWriteCellStyle.setWriteFont(contentWriteFont);//在样式用应用设置的字体;
  101. //设置样式;
  102. contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);//设置底边框;
  103. contentWriteCellStyle.setBottomBorderColor((short) 0);//设置底边框颜色;
  104. contentWriteCellStyle.setBorderLeft(BorderStyle.THIN); //设置左边框;
  105. contentWriteCellStyle.setLeftBorderColor((short) 0);//设置左边框颜色;
  106. contentWriteCellStyle.setBorderRight(BorderStyle.THIN);//设置右边框;
  107. contentWriteCellStyle.setRightBorderColor((short) 0);//设置右边框颜色;
  108. contentWriteCellStyle.setBorderTop(BorderStyle.THIN);//设置顶边框;
  109. contentWriteCellStyle.setTopBorderColor((short) 0); ///设置顶边框颜色;
  110. contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);// 水平居中
  111. contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
  112. contentWriteCellStyle.setWrapped(true); //设置自动换行;
  113. contentWriteCellStyle.setDataFormat((short)49);//设置单元格格式是:文本格式,方式长数字文本科学计数法
  114. contentWriteCellStyle.setShrinkToFit(true);//设置文本收缩至合适
  115. return contentWriteCellStyle;
  116. }
  117. }

3、导出的时候,特殊数据类型,需要设置转换类,不然注解导出方式会报错

        注解使用方式

  1. @ExcelProperty(value = "进站日期", converter = LocalDateTimeConverter.class, index = 20)
  2. private LocalDateTime arriveTime;

        日期转换类

  1. package com.xinba.statistical.rules.base.utils.excel;
  2. import com.alibaba.excel.converters.Converter;
  3. import com.alibaba.excel.enums.CellDataTypeEnum;
  4. import com.alibaba.excel.metadata.CellData;
  5. import com.alibaba.excel.metadata.GlobalConfiguration;
  6. import com.alibaba.excel.metadata.property.DateTimeFormatProperty;
  7. import com.alibaba.excel.metadata.property.ExcelContentProperty;
  8. import java.time.LocalDateTime;
  9. import java.time.format.DateTimeFormatter;
  10. public class LocalDateTimeConverter implements Converter<LocalDateTime> {
  11. private static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
  12. @Override
  13. public Class<LocalDateTime> supportJavaTypeKey() {
  14. return LocalDateTime.class;
  15. }
  16. @Override
  17. public CellDataTypeEnum supportExcelTypeKey() {
  18. return CellDataTypeEnum.STRING;
  19. }
  20. @Override
  21. public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
  22. GlobalConfiguration globalConfiguration) {
  23. DateTimeFormatProperty dateTimeFormatProperty = contentProperty.getDateTimeFormatProperty();
  24. String dateTimeFormatPattern = DEFAULT_DATETIME_FORMAT;
  25. if(null != dateTimeFormatProperty){
  26. dateTimeFormatPattern = dateTimeFormatProperty.getFormat();
  27. }
  28. return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern(dateTimeFormatPattern));
  29. }
  30. @Override
  31. public CellData<String> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty,
  32. GlobalConfiguration globalConfiguration) {
  33. DateTimeFormatProperty dateTimeFormatProperty = contentProperty.getDateTimeFormatProperty();
  34. String dateTimeFormatPattern = DEFAULT_DATETIME_FORMAT;
  35. if(null != dateTimeFormatProperty){
  36. dateTimeFormatPattern = dateTimeFormatProperty.getFormat();
  37. }
  38. return new CellData<>(value.format(DateTimeFormatter.ofPattern(dateTimeFormatPattern)));
  39. }
  40. }

此转换类中的easyExcel 3.3.2版本中,变成了WriteCellData, 具体参考Converter<T>接口中的声明,适当调整即可


4、web导出excel(将excel数据写入到response输出流中)

  1. // 直接用浏览器或者用postman
  2. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  3. response.setCharacterEncoding("utf-8");
  4. // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
  5. String fileName = String.format("文件名称"+System.currentTimeMillis(), taskCode);
  6. fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
  7. response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
  8. OutputStream out = response.getOutputStream();
  9. // 设置单元格样式
  10. HorizontalCellStyleStrategy horizontalCellStyleStrategy =
  11. new HorizontalCellStyleStrategy(StyleUtils.getHeadStyle(), StyleUtils.getContentStyle());
  12. // 列宽策略设置
  13. ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();
  14. ExcelWriter excelWriter = EasyExcel.write(out)
  15. .registerWriteHandler(horizontalCellStyleStrategy)
  16. .registerWriteHandler(widthStyleStrategy)
  17. .build();
  18. // 总体统计 sheet
  19. WriteSheet totalSheet = EasyExcel.writerSheet(0, "总体统计").head(StatisticsAnalyseDivisorVo.class).build();
  20. excelWriter.write(total,totalSheet);
  21. // web导出,这里必须要有这个finish,不然导出的文件是空的,官方文档的案例没写
  22. excelWriter.finish();

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/812274
推荐阅读
相关标签
  

闽ICP备14008679号