HttpServletResponse输出excel文件代码
时间: 2023-08-18 20:23:47 浏览: 175
以下是使用HttpServletResponse输出Excel文件的Java代码示例:
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置响应头信息,提示浏览器下载文件
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("example.xlsx", "UTF-8"));
// 创建Excel文件
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue("Hello World!");
// 将Excel文件写入响应流
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
// 关闭资源
outputStream.flush();
outputStream.close();
workbook.close();
}
```
注意,此代码使用了Apache POI库来创建和操作Excel文件。在实际使用中,需要添加POI库的依赖。
阅读全文