springboot导出execl表格
时间: 2023-09-01 15:13:04 浏览: 94
1.添加依赖
在pom.xml文件中添加以下依赖:
```
<!-- Excel导出依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
```
2.编写控制器
在控制器中编写导出Excel的方法:
```
@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
// 1.创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 2.创建工作表
XSSFSheet sheet = workbook.createSheet("用户信息");
// 3.创建行
XSSFRow row = sheet.createRow(0);
// 4.创建单元格
XSSFCell cell = row.createCell(0);
cell.setCellValue("用户名");
cell = row.createCell(1);
cell.setCellValue("年龄");
cell = row.createCell(2);
cell.setCellValue("性别");
// 5.写入数据
List<User> userList = userService.getUserList();
for (int i = 0; i < userList.size(); i++) {
row = sheet.createRow(i + 1);
User user = userList.get(i);
row.createCell(0).setCellValue(user.getName());
row.createCell(1).setCellValue(user.getAge());
row.createCell(2).setCellValue(user.getGender());
}
// 6.设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=userInfo.xlsx");
// 7.输出Excel
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
```
3.测试
启动SpringBoot应用,访问导出Excel的接口,即可下载Excel文件。
阅读全文