springboot 导出excel
时间: 2023-05-08 13:58:46 浏览: 160
Spring Boot是一个快速开发框架,Spring Boot的特点是可以快速开发,容易组合,简洁,生产就绪等等。而导出Excel文件也是常用的需求,为了方便大家,Spring Boot提供了一些简单的方式来导出Excel文件。
首先,需要引入以下依赖:
```
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
```
接着,需要定义一个数据类,并在该类中定义对应的属性,如下:
```
@Data
public class ExcelData {
private String name;
private Integer age;
private String address;
}
```
在Controller中定义一个返回Excel文件的接口,如下:
```
@RequestMapping("/downloadExcel")
public void downloadExcel(HttpServletResponse response) throws IOException {
// 创建Excel workbook对象
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建Excel sheet对象
XSSFSheet sheet = workbook.createSheet("学生信息");
// 定义表头
XSSFRow header = sheet.createRow(0);
header.createCell(0).setCellValue("姓名");
header.createCell(1).setCellValue("年龄");
header.createCell(2).setCellValue("地址");
// 添加数据
List<ExcelData> dataList = new ArrayList<>();
dataList.add(new ExcelData("张三", 20, "北京"));
dataList.add(new ExcelData("李四", 25, "上海"));
dataList.add(new ExcelData("王五", 30, "广州"));
for (int i = 0; i < dataList.size(); i++) {
XSSFRow row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(dataList.get(i).getName());
row.createCell(1).setCellValue(dataList.get(i).getAge());
row.createCell(2).setCellValue(dataList.get(i).getAddress());
}
// 设置下载文件名以及响应头
response.setHeader("Content-Disposition", "attachment;filename=student.xlsx");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// 输出Excel文件
workbook.write(response.getOutputStream());
}
```
最后,在浏览器中访问该接口,即可下载Excel文件student.xlsx。
上面是基于Spring Boot导出Excel表格的简单流程,我们完全可以根据需求对其中的样式和结构进行定制和完善,例如通过自定义Excel样式和数据源来获得更好的导出效果。
阅读全文
相关推荐

















