springboot 快速导出excel
时间: 2023-10-13 17:20:00 浏览: 78
springboot导出excel
5星 · 资源好评率100%
1. 添加依赖
在 pom.xml 中添加以下依赖:
```xml
<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>
```
2. 编写导出方法
在 Controller 中编写导出方法,如下所示:
```java
@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
// 创建 workbook
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
// 设置表头
XSSFRow header = sheet.createRow(0);
header.createCell(0).setCellValue("姓名");
header.createCell(1).setCellValue("年龄");
header.createCell(2).setCellValue("性别");
// 填充数据
List<User> userList = userService.findAll();
int rowNum = 1;
for (User user : userList) {
XSSFRow row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(user.getName());
row.createCell(1).setCellValue(user.getAge());
row.createCell(2).setCellValue(user.getGender());
}
// 设置响应头
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户列表.xlsx", "utf-8"));
// 输出文件
workbook.write(response.getOutputStream());
}
```
3. 测试导出
启动应用,访问导出接口即可下载 Excel 文件。
阅读全文