SpringBoot导出Excel的四种方式
SpringBoot导出Excel有多种方式,以下是四种常用的方法:
- 使用Apache POI
Apache POI是Apache软件基金会的开源函式库,用于操作Microsoft Office文档。
@GetMapping("/download")
public void downloadExcel(HttpServletResponse response) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Users");
// 创建标题行
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("ID");
titleCell.setCellValue("Name");
// 填充数据
Row row = sheet.createRow(1);
row.createCell(0).setCellValue(1);
row.createCell(1).setCellValue("John Doe");
// 设置响应头
response.setHeader("Content-Disposition", "attachment; filename=\"users.xlsx\"");
response.setStatus(HttpServletResponse.SC_OK);
// 写入到输出流
workbook.write(response.getOutputStream());
workbook.close();
}
- 使用EasyExcel
EasyExcel是阿里巴巴开源的一个Excel处理框架,它有很好的性能,并且使用简单。
@GetMapping("/download")
public void downloadExcel(HttpServletResponse response) throws IOException {
response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
response.setContentType("application/vnd.ms-excel");
EasyExcel.write(response.getOutputStream(), DemoData.class)
.sheet("模板")
.doWrite(data());
}
private List<DemoData> data() {
List<DemoData> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new DemoData("a" + i, i));
}
return list;
}
- 使用JExcel
JExcel是一个轻量级的Java库,用于在服务器端创建和修改Excel文件。
@GetMapping("/download")
public void downloadExcel(HttpServletResponse response) throws IOException {
response.setHeader("Content-Disposition", "attachment;filename=test.xls");
response.setContentType("application/vnd.ms-excel");
WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
WritableSheet sheet = workbook.createSheet("Sheet1", 0);
// 添加标题
Label label = new Label(0, 0, "ID");
sheet.addCell(label);
label = new Label(1, 0, "Name");
sheet.addCell(label);
// 添加数据
for (int i = 0; i < 10; i++) {
label = new Label(0, i + 1, "a" + i);
sheet.addCell(label);
label = new Label(1, i + 1, i);
sheet.addCell(label);
}
workbook.write();
workbook.close();
}
- 使用OpenCSV
OpenCSV是一个
评论已关闭