欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > 开发日记-EaxyExcel修改模板sheet名称

开发日记-EaxyExcel修改模板sheet名称

2024/11/30 9:28:58 来源:https://blog.csdn.net/V_S1r/article/details/141397734  浏览:    关键词:开发日记-EaxyExcel修改模板sheet名称

引入pom:

<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel-core</artifactId><version>3.1.1</version><scope>compile</scope></dependency>

编写自定义拦截器:


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;}@Overridepublic void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {}/*** 功能:动态修改模板中sheet的名称* sheet创建完成后调用* @param writeWorkbookHolder* @param writeSheetHolder*/@Overridepublic void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {if (sheetName == null) {return;}if (sheetNo == null) {sheetNo = 0;}writeWorkbookHolder.getCachedWorkbook().setSheetName(sheetNo, sheetName);}
}

生成excel代码:

// ...省略外层接口逻辑
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();}
// 省略后续逻辑

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com