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);
}

浙公网安备 33010602011771号