怎么在SpringBoot中利用POI下载Excel文件
发布时间:2023-05-17 14:27:37
SpringBoot是一个快速开发Java应用的框架,支持各种嵌入式的web容器,并提供了多种常用的开发配置,能够快速搭建一个基于Java的Web应用。而POI是Java开发Excel文件的常用库之一,可以方便地处理Excel文件,包括生成、读取和编辑等。本文将介绍如何在SpringBoot中利用POI下载Excel文件。
首先需要在pom.xml中添加相关的依赖:
<!-- 生成Excel文件所需的依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
<scope>compile</scope>
</dependency>
接下来,我们创建一个Controller类,实现Excel文件的下载。
@RestController
public class ExcelController {
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadExcel(HttpServletRequest request) throws IOException {
// 生成Excel文件
Workbook workbook = createWorkbook();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
workbook.write(bos);
} finally {
bos.close();
}
byte[] content = bos.toByteArray();
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
String filename = "test.xls";
// 中文乱码解决
String userAgent = request.getHeader("User-Agent");
if (userAgent != null && userAgent.indexOf("MSIE") != -1 || userAgent.indexOf("Trident") != -1) {
filename = java.net.URLEncoder.encode(filename, "UTF-8");
} else {
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
}
headers.setContentDispositionFormData("attachment", filename);
// 返回Excel文件
return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
}
// 创建Excel文件
private Workbook createWorkbook() {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("test");
// 设置单元格宽度
sheet.setColumnWidth(0, 256 * 20);
// 创建表头
Row headerRow = sheet.createRow(0);
Cell headerCell = headerRow.createCell(0);
headerCell.setCellValue("姓名");
headerCell = headerRow.createCell(1);
headerCell.setCellValue("性别");
headerCell = headerRow.createCell(2);
headerCell.setCellValue("年龄");
// 创建数据行
for (int i = 1; i <= 1000; i++) {
Row dataRow = sheet.createRow(i);
Cell dataCell = dataRow.createCell(0);
dataCell.setCellValue("测试" + i);
dataCell = dataRow.createCell(1);
dataCell.setCellValue("男");
dataCell = dataRow.createCell(2);
dataCell.setCellValue(20 + i);
}
return workbook;
}
}
上述代码中,我们创建了一个/download的GET请求,用于下载Excel文件。在方法中,首先利用POI生成一个Workbook对象,然后将其输出到一个ByteArrayOutputStream流对象中,最后返回一个字节数组及设置响应头,实现文件的下载。
其中,我们通过设置响应头的Content-Disposition属性,实现了文件下载后的文件名。由于中文文件名容易出现乱码,我们利用了对User-Agent头的特殊判断,将文件名转换为ISO8859-1编码后再设置到响应头中。
另外,我们生成了一个简单的Excel文件,包含了一个表头和1000条数据记录。
最后,启动SpringBoot应用,访问http://localhost:8080/download,即可下载Excel文件。
