java将poi生成的excel文件以流的形式通过请求返回给前端
时间: 2023-12-26 10:06:30 浏览: 131
可以通过以下步骤将poi生成的excel文件以流的形式通过请求返回给前端:
1. 使用poi创建excel文件并将其写入OutputStream中:
```java
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello World!");
OutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
```
2. 将OutputStream转换为ByteArrayInputStream:
```java
ByteArrayInputStream inputStream = new ByteArrayInputStream(((ByteArrayOutputStream) outputStream).toByteArray());
```
3. 在返回响应时,将ByteArrayInputStream中的内容写入response的输出流中:
```java
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, len);
}
inputStream.close();
```
完整代码示例:
```java
@RequestMapping("/downloadExcel")
public void downloadExcel(HttpServletResponse response) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello World!");
OutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
ByteArrayInputStream inputStream = new ByteArrayInputStream(((ByteArrayOutputStream) outputStream).toByteArray());
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, len);
}
inputStream.close();
}
```
阅读全文