HFFSWorkBook下载(Apache POI)+ servlet响应

时间:2016-10-30 14:16:06

标签: excel servlets stream apache-poi

我想下载包含内容的.xls文件。 这是我编写的根据我的要求处理.xls文件然后下载它的方法。

 public static void readDataFromResponse(String csvData, String fileName,
    HttpServletResponse response) throws IOException{
    if(!csvData.isEmpty()){
        BufferedReader br = null;
        byte[] binaryData = csvData.getBytes(Charset.forName("UTF-8"));
        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFSheet sheet = workBook.createSheet(fileName);
          // do something to insert values into excel.
        }

        response.setHeader("Content-Length", "" + Integer.toString(binaryData.length));
        response.setContentType("application/ms-excel");
        response.addHeader("Content-Disposition",String.join("","attachment; filename=" + fileName + ".xls"));
        response.addHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0");

       //XLS file is downloaded but it is in binary. Not human readable
        OutputStream outputStream = response.getOutputStream();
        workBook.write(outputStream);
        outputStream.flush();
    }

使用此代码导出excel,但内容不可读。我得到工作簿的二进制表示。如何使用可读的数据导出Excel?

1 个答案:

答案 0 :(得分:1)

您需要设置HttpResponse对象的正确值

实施例

对于.Xls文件

response.setHeader("Content-Type", application/vnd.ms-excel);
response.setCharacterEncoding("UTF-8");

对于Excel2007及更高版本的.xlsx文件

response.setCharacterEncoding("UTF-8");    
response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");