注意事项
更新于2023/8/30.
表现:就是监听类的数据,读取不到,全部为null
导出
@ApiOperation("模板下载")
@GetMapping("/template/downLoad")
public String attributeTemplateDownload(HttpServletResponse response) throws IOException {
//自动关流
try(ServletOutputStream outputStream = response.getOutputStream();) {
String fileName = new String("AttributeUploadTemplate.xlsx".getBytes(), StandardCharsets.ISO_8859_1);
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
// 这个list用于装数据,就是表头下显示的东西
List<TrackAttributePO> list = new ArrayList<>();
// 流 实体类 页名 数据
EasyExcel.write(outputStream, TrackAttributePO.class).sheet("sheet1").doWrite(list);
} catch (IOException e) {
e.printStackTrace();
log.error("模板下载异常", e);
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = MapUtils.newHashMap();
map.put("status", "failure");
map.put("message", "下载文件失败" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}
return "success";
}
}
导入
这是监听器:
package com.chinamobile.cmss.guard.apm.buringpoint.manage.util;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.chinamobile.cmss.guard.apm.buringpoint.manage.mapper.AttributeValueManagementMapper;
import com.chinamobile.cmss.guard.apm.buringpoint.manage.po.TrackAttributePO;
import com.chinamobile.cmss.guard.apm.buringpoint.manage.po.TrackAttributeValuePO;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Slf4j
public class TrackAttributeValueReadListener implements ReadListener<TrackAttributeValuePO> {
/**
* 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
*/
private static final int BATCH_COUNT = 5;
private List<TrackAttributeValuePO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
private AttributeValueManagementMapper attributeValueManagementMapper;
public TrackAttributeValueReadListener(AttributeValueManagementMapper attributeValueManagementMapper) {
this.attributeValueManagementMapper = attributeValueManagementMapper;
}
@Override
public void invoke(TrackAttributeValuePO row, AnalysisContext context) {
row.setUpdateTime(new Date());
row.setCreator("system");
row.setModifier("system");
row.setCreateTime(new Date());
row.setDelTag(0);
cachedDataList.add(row);
if (cachedDataList.size() >= BATCH_COUNT) {
attributeValueManagementMapper.batchInsertData(cachedDataList);
// 存储完成清理 list
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
System.out.println("读取完毕");
}
}
监听器读取表头
写在监听器里
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
//获取表头,无法保证headMap的顺序与Excel的表头顺序一致
if (headerList == null) {
headerList = new ArrayList<>();
}
List<String> header = new ArrayList<>();
for (int i = 0; i < headMap.size(); i++) {
header.add(headMap.get(i));
}
headerList.add(header);
}
多sheet页
// 初始化Excel写入器
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).head(headsFromVO(customizeHeads)).build();
// 遍历所有的数据集合,并为每个数据集合创建一个新的sheet
for (int i = 0; i < allSheetData.size(); i++) {
List<TrackBusinessCodePO> sheetData = allSheetData.get(i);
// 将PO对象列表转换为Map列表
List<Map<String, Object>> dataMapList = BeanUtils.beansToMaps(sheetData);
// 根据定制的表头映射数据
List<List<Object>> formattedData = mapDataForExport(dataMapList, customizeHeads);
// 获取sheet的名称
String sheetName = sheetList.get(i).getSheetName();
// 创建新的sheet
WriteSheet sheet = EasyExcel.writerSheet(sheetName).build();
// 将数据写入到新的sheet中
excelWriter.write(formattedData, sheet);
}
//参考二
// 在控制层中的相应方法中调用此函数
public void exportMultiSheetExcel(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 设置文件名编码,防止乱码
String fileName = URLEncoder.encode("多Sheet页导出示例", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
// 创建输出流
OutputStream outputStream = response.getOutputStream();
// 写入数据到Excel
ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
// 写入第一个sheet页
WriteSheet sheet1 = EasyExcel.writerSheet(0, "Sheet1").head(Sheet1Data.class).build();
List<Sheet1Data> sheet1DataList = getSheet1Data();
excelWriter.write(sheet1DataList, sheet1);
// 写入第二个sheet页
WriteSheet sheet2 = EasyExcel.writerSheet(1, "Sheet2").head(Sheet2Data.class).build();
List<Sheet2Data> sheet2DataList = getSheet2Data();
excelWriter.write(sheet2DataList, sheet2);
// 写入更多的sheet页...
excelWriter.finish();
outputStream.close();
}
easyexcel中的常用编码方式
Alibaba EasyExcel:使用CellWriteHandler 为单元格 设置格式与样式,版本 2.2.6+ :
参考:https://blog.csdn.net/weixin_42151235/article/details/128333199
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 水平居中
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 垂直居中
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置自动换行,前提内容中需要加「\n」才有效
contentWriteCellStyle.setWrapped(true);
// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
WriteSheet writeSheet = EasyExcel
.writerSheet().head(UserTest.class)
.registerWriteHandler(horizontalCellStyleStrategy)
.build();
/**
* 默认样式
* @return
*/
public static HorizontalCellStyleStrategy defaultStyles(){
//TODO 默认样式
//表头样式策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//设置表头居中对齐
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//表头前景设置淡蓝色
headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setBold(true);
headWriteFont.setFontName("宋体");
headWriteFont.setFontHeightInPoints((short) 12);
headWriteCellStyle.setWriteFont(headWriteFont);
//内容样式策略策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 设置背景颜色白色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
// 设置垂直居中为居中对齐
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置左右对齐为靠左对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
// 设置单元格上下左右边框为细边框
contentWriteCellStyle.setBorderBottom(BorderStyle.MEDIUM);
contentWriteCellStyle.setBorderLeft(BorderStyle.MEDIUM);
contentWriteCellStyle.setBorderRight(BorderStyle.MEDIUM);
contentWriteCellStyle.setBorderTop(BorderStyle.MEDIUM);
//创建字体对象
WriteFont contentWriteFont = new WriteFont();
//内容字体大小
contentWriteFont.setFontName("宋体");
contentWriteFont.setFontHeightInPoints((short) 14);
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 初始化表格样式
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
return horizontalCellStyleStrategy;
}
easyexcel中的常用注解
备注:部分未能成功使用,所以我选择了编码方式
参考:easyexcel中的常用注解_想养一只!的博客-CSDN博客
@ExcelProperty
@ColumnWith 列宽
@ContentFontStyle 文本字体样式
@ContentLoopMerge 文本合并
@ContentRowHeight 文本行高度
@ContentStyle 文本样式
@HeadFontStyle 标题字体样式
@HeadRowHeight 标题高度
@HeadStyle 标题样式
@ExcelIgnore 忽略项
@ExcelIgnoreUnannotated 忽略未注解
字段注解 | 类注解 |
@ColumnWith(列宽) | @ColumnWidth(全局列宽) |
@ExcelProperty(字段配置) | @HeadFontStyle(头样式) |
@HeadRowHeight(标题高度) | |
@ContentFontStyle(内容字体样式) | |
@ContentRowHeight(内容高度) |
@ExcelProperty
必要的一个注解,注解中有三个参数value,index分别代表列明,列序号
value和index只能二选一,通常不用设置converter
1.value 通过标题文本对应
2.index 通过文本行号对应
@ExcelProperty(value = "人员姓名",index = 1)
private String comparisonName;
1
2
@ColumnWith
设置列宽度,只有一个参数value,value的单位是字符长度,最大可以设置255个字符,因为一个excel单元格最大可以写入的字符个数就是255个字符
@ContentFontStyle
用于设置单元格内容字体格式的注解
参数 | 含义 |
fontName | 字体名称 |
fontHeightInPoints | 字体高度 |
italic | 是否斜体 |
strikeout | 是否设置删除水平线 |
color | 字体颜色 |
typeOffset | 偏移量 |
underline | 下划线 |
bold | 是否加粗 |
charset | 编码格式 |
@ContentStyle
设置内容格式注解
参数 | 含义 |
dataFormat | 日期格式 |
hidden | 设置单元格使用此样式隐藏 |
locked | 设置单元格使用此样式锁定 |
quotePrefix | 在单元格前面增加`符号,数字或公式将以字符串形式展示 |
horizontalAlignment | 设置是否水平居中 |
wrapped | 设置文本是否应换行。将此标志设置为true通过在多行上显示使单元格中的所有内容可见 |
verticalAlignment | 设置是否垂直居中 |
rotation | 设置单元格中文本旋转角度。03版本的Excel旋转角度区间为-90°90°,07版本的Excel旋转角度区间为0°180° |
indent | 设置单元格中缩进文本的空格数 |
borderLeft | 设置左边框的样式 |
borderRight | 设置右边框样式 |
borderTop | 设置上边框样式 |
borderBottom | 设置下边框样式 |
leftBorderColor | 设置左边框颜色 |
rightBorderColor | 设置右边框颜色 |
topBorderColor | 设置上边框颜色 |
bottomBorderColor | 设置下边框颜色 |
fillPatternType | 设置填充类型 |
fillBackgroundColor | 设置背景色 |
fillForegroundColor | 设置前景色 |
shrinkToFit | 设置自动单元格自动大小 |
@HeadFontStyle
用于定制标题字体格式
参数 | 含义 |
fontName | 设置字体名称 |
fontHeightInPoints | 设置字体高度 |
italic | 设置字体是否斜体 |
strikeout | 是否设置删除线 |
color | 设置字体颜色 |
typeOffset | 设置偏移量 |
underline | 设置下划线 |
charset | 设置字体编码 |
bold | 设置字体是否加粗 |
@ExcelIgnore
不将该字段转换成Excel
颜色对照表
颜色对照表:
颜色 测试 Class名称 short
Test颜色 Black 8
Test颜色 Brown 60
Test颜色 Olive_Green 59
Test颜色 Dark_Green 58
Test颜色 Dark_Teal 56
Test颜色 Dark_Blue 18
Test颜色 Indigo 62
Test颜色 Grey_80_PERCENT 63
Test颜色 Dark_Red 16
Test颜色 Orange 53
Test颜色 DARK_YELLOW 19
Test颜色 Green 17
Test颜色 Teal 21
Test颜色 Blue 12
Test颜色 Blue_Grey 54
Test颜色 Grey_50_PERCENT 23
Test颜色 Red 10
Test颜色 LIGHT_ORANGE 52
Test颜色 LIME 50
Test颜色 SEA_GREEN 57
Test颜色 AQUA 49
Test颜色 LIGHT_BLUE 48
Test颜色 VIOLET 20
Test颜色 GREY_40_PERCENT 55
Test颜色 Pink 14
Test颜色 Gold 51
Test颜色 Yellow 13
Test颜色 BRIGHT_GREEN 11
Test颜色 TURQUOISE 15
Test颜色 SKY_BLUE 40
Test颜色 Plum 61
Test颜色 GREY_25_PERCENT 22
Test颜色 Rose 45
Test颜色 Tan 47
Test颜色 LIGHT_YELLOW 43
Test颜色 LIGHT_GREEN 42
Test颜色 LIGHT_TURQUOISE 41
Test颜色 PALE_BLUE 44
Test颜色 LAVENDER 46
Test颜色 White 9
Test颜色 CORNFLOWER_BLUE 24
Test颜色 LEMON_CHIFFON 26
Test颜色 MAROON 25
Test颜色 ORCHID 28
Test颜色 CORAL 29
Test颜色 ROYAL_BLUE 30
Test颜色 LIGHT_CORNFLOWER_BLUE 31
Test颜色 AUTOMATIC 64