java如何把数据导出到Excel文件
1、首先导入依赖
<!--easyExcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
<!-- POI导入导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
2、在我们要导出的实体类上加上表头和表格长和宽,这里我写了一个People类,作为示例
@Data
@ColumnWidth(25)
@HeadRowHeight(20)
@ContentRowHeight(18)
public class Person {
//添加表头
@ExcelProperty(value = "姓名")
private String name;
@ExcelProperty(value = "爱好")
private String hobby;
}
3、写一个用于导出的接口(前端接入即可下载)
@GetMapping("demo")
public void demo(HttpServletResponse response) throws Exception {
//构建People的list集合
Person person = new Person();
person.setName("张三");
person.setHobby("唱歌");
List<Person> personList = new ArrayList<>();
personList.add(person);
//服务器告诉客户端(通常是Web浏览器)正在发送的数据是Excel文件
response.setContentType("application/vnd.ms-excel");
//服务器告诉客户端(通常是Web浏览器),响应中的文本数据使用UTF-8编码进行编码
response.setCharacterEncoding(Charsets.UTF_8.name());
//设置文件名
String fileName = URLEncoder.encode("个人数据" , Charsets.UTF_8.name());
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//使用EasyExcel库将数据导出为Excel文件,并通过HTTP响应将生成的Excel文件发送到客户端进行下载。
EasyExcel.write(response.getOutputStream(), People.class).sheet("个人数据表").doWrite(peopleList);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了