引入pom:
XML
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel-core</artifactId>
<version>3.1.1</version>
<scope>compile</scope>
</dependency>
编写自定义拦截器:
java
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* 自定义模板导出sheet拦截器
*/
public class CustomTemplateSheetStrategy implements SheetWriteHandler {
private Integer sheetNo;
private String sheetName;
public CustomTemplateSheetStrategy(String sheetName) {
this.sheetName = sheetName;
}
public CustomTemplateSheetStrategy(Integer sheetNo, String sheetName) {
this.sheetNo = sheetNo;
this.sheetName = sheetName;
}
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
/**
* 功能:动态修改模板中sheet的名称
* sheet创建完成后调用
* @param writeWorkbookHolder
* @param writeSheetHolder
*/
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
if (sheetName == null) {
return;
}
if (sheetNo == null) {
sheetNo = 0;
}
writeWorkbookHolder.getCachedWorkbook().setSheetName(sheetNo, sheetName);
}
}
生成excel代码:
java
// ...省略外层接口逻辑
try (//文件模板输入流
InputStream inputStream = new ClassPathResource("//使用系统路径+文件名").getInputStream();
ExcelWriter excelWriter = EasyExcelFactory.write(getOutputStream(fileName, response))
.withTemplate(inputStream)
.registerWriteHandler(new CustomTemplateSheetStrategy(0//sheet序号,从0开始 , "// 自定义sheet名称"))
.autoCloseStream(Boolean.TRUE)
.build()) {
WriteSheet sheet0 = EasyExcelFactory.writerSheet(0, "基本信息表").build();
//填充配置:forceNewRow为true列表自动换行
FillConfig fillConfig = FillConfig.builder().forceNewRow(true).build();
// 填充
excelWriter.fill(// 数据, sheet0);
// 填充完成
excelWriter.finish();
} catch (IOException e) {
e.printStackTrace();
}
// 省略后续逻辑