Hutool Java 工具类库导出 Excel,2步搞定!
Java开发宝典
共 2905字,需浏览 6分钟
·
2021-07-29 05:38
前言
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
@RequestMapping("/export")
@ResponseBody
public void export(HttpServletResponse response){
List<User> list = new ArrayList<>();
list.add(new User("zhangsan","1231",new Date()));
list.add(new User("zhangsan1","1232",new Date()));
list.add(new User("zhangsan2","1233",new Date()));
list.add(new User("zhangsan3","1234",new Date()));
list.add(new User("zhangsan4","1235",new Date()));
list.add(new User("zhangsan5","1236", DateUtil.date(new Date())));
// 通过工具类创建writer,默认创建xls格式
ExcelWriter writer = ExcelUtil.getWriter();
//自定义标题别名
writer.addHeaderAlias("name", "姓名");
writer.addHeaderAlias("age", "年龄");
writer.addHeaderAlias("birthDay", "生日");
// 合并单元格后的标题行,使用默认标题样式
writer.merge(2, "申请人员信息");
// 一次性写出内容,使用默认样式,强制输出标题
writer.write(list, true);
//out为OutputStream,需要写出到的目标流
//response为HttpServletResponse对象
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
String name = StringUtils.toUtf8String("申请学院");
response.setHeader("Content-Disposition","attachment;filename="+name+".xls");
ServletOutputStream out= null;
try {
out = response.getOutputStream();
writer.flush(out, true);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
// 关闭writer,释放内存
writer.close();
}
//此处记得关闭输出Servlet流
IoUtil.close(out);
}
来源:https://urlify.cn/iu26vy
分享一下我写的《10万字Springboot经典学习笔记》中,点击下面小卡片,进入【Java秃头哥】,回复:笔记,即可免费获取。
点赞是最大的支持
评论