根据复杂excel文档模板导出excel表格
1,首先导入阿里的jar包
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.0.2</version> </dependency> |
2,将模板excel文件放在对应目录下,取文件时根据存放路径取
①模板内容
②模板存放位置
3,编写util类
public class TemplateExcelUtils{
/**
* 导出文件时为Writer生成OutputStream.
* @param fileName 文件名
* @param response response
* @return ""
*/
public static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
return response.getOutputStream();
} catch (IOException e) {
throw new Exception("导出excel表格失败!", e);
}
}
}
4,编写测试代码
@RestController
@RequestMapping("/user")
public class ExcelTest {
@GetMapping("/downExcelTest")
public void downExcel2(HttpServletResponse response) {
InputStream is= null;
Map<String, Object> map = new HashMap<>();
map.put("nowDay", "2023-06-13");
map.put("customerName", "测试客户名");
map.put("customerNo", "测试客户编号");
map.put("solutiomTime", "2023-06-09");
map.put("amount", "2000");
map.put("userName", "张三");
map.put("taskNo", "202306130001");
map.put("taskNo", "1001");
map.put("processingTime", "2023-06-09");
map.put("longAmount", "500");
map.put("shortAmount", "300");
map.put("accountNo", "CN20230613");
// 取出模板
try {
is = ResourceUtil.getStream("templates/ErrorAccInfo.xlsx");
//定义最终导出的文件名称
String fileName = "测试文档.xlsx";
ExcelWriter excelWriter = EasyExcel.write(TemplateExcelUtils.getOutputStream(fileName, response)).withTemplate(is).excelType(ExcelTypeEnum.XLSX).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
// 这个传进去的 map 就是非表格数据
excelWriter.fill(map, writeSheet);
excelWriter.finish();
} catch(Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5,测试。启动项目后打开浏览器输入对应地址
6,测试结果
个人日常学习记录
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤