将XSSFWorkbook excel文件写入响应流

时间:2018-05-27 15:34:54

标签: java excel response

我有这个网页 单击按钮时,它会读取数据并将文件保存到xyz位置。

我不想那样。我想通过Chrome浏览器降低负载。

我如何发送以下回复?

给出错误的行是response.getOutputStream().write(outputStream);

由于

public void exportCOAExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {

    //works well. save excel file to desktop
    XSSFWorkbook workbook = new XSSFWorkbook ();
    FileOutputStream outputStream = new FileOutputStream("C:\\Users\\user\\Desktop\\revenue.xls");
    workbook.write(outputStream);
    outputStream.flush();
    outputStream.close();

   //trying to get browser to download the file
    response.setContentType("text/xls");
    response.setHeader("Content-disposition", "attachment;filename=" + "a.xls");

   /************problematic line************/
   response.getOutputStream().write(outputStream);

    response.getOutputStream().flush();

}

1 个答案:

答案 0 :(得分:0)

您可以将workbook直接写入回复outputstream

XSSFWorkbook workbook = new XSSFWorkbook();
response.setContentType("text/xls");
response.setHeader("Content-disposition", "attachment;filename=" + "a.xls");

try (OutputStream outputStream = response.getOutputStream()) {
     workbook.write(outputStream);
}