怎么用springboot实现excel导出
时间: 2023-06-06 21:05:59 浏览: 113
使用Springboot实现excel的导入导出
您可以使用POI库来实现SpringBoot中的Excel导出功能。首先需要在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
然后可以创建一个ExcelUtils类来实现Excel导出功能。以下是一个示例代码:
```
public class ExcelUtils {
public static void exportExcel(HttpServletResponse response, List<?> dataList, String fileName, String sheetName) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(sheetName);
XSSFRow row;
XSSFCell cell;
int rowNum = 0;
row = sheet.createRow(rowNum++);
// 添加表头
List<String> headers = Arrays.asList("ID", "Name", "Age");
for (int i = 0; i < headers.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(headers.get(i));
}
// 往Excel表格中添加数据
for (Object data : dataList) {
row = sheet.createRow(rowNum++);
// 获取data的属性值
int id = BeanUtils.getProperty(data, "id");
String name = BeanUtils.getProperty(data, "name");
int age = BeanUtils.getProperty(data, "age");
row.createCell(0).setCellValue(id);
row.createCell(1).setCellValue(name);
row.createCell(2).setCellValue(age);
}
// 设置响应头
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream outputStream;
try {
outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
您可以在任何SpringBoot的Controller中使用ExcelUtils类来导出Excel。例如,以下是一个基于HTTP GET请求的Controller:
```
@GetMapping("/exportExcel")
public void exportExcel(HttpServletResponse response) {
List<User> userList = userService.getAllUsers();
ExcelUtils.exportExcel(response, userList, "User List", "Sheet1");
}
```
阅读全文