java导出数据到excel并在浏览器下载
时间: 2023-06-16 07:03:14 浏览: 64
要在Java中将数据导出到Excel并在浏览器中下载,可以使用Apache POI库。以下是一个示例代码:
```java
// 创建工作簿对象
Workbook workbook = new XSSFWorkbook();
// 创建工作表对象
Sheet sheet = workbook.createSheet("Sheet1");
// 创建表头行及单元格
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("列1");
headerRow.createCell(1).setCellValue("列2");
headerRow.createCell(2).setCellValue("列3");
// 填充数据
Row dataRow = sheet.createRow(1);
dataRow.createCell(0).setCellValue("数据1");
dataRow.createCell(1).setCellValue("数据2");
dataRow.createCell(2).setCellValue("数据3");
// 设置响应头信息
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=data.xlsx");
// 将工作簿写入输出流
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
```
在该代码中,首先使用`Workbook`和`Sheet`对象创建工作簿和工作表。接着创建表头行及单元格,并填充数据。最后,设置响应头信息,将工作簿写入输出流并将其发送到浏览器进行下载。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)