HFFSWorkBook下载(Apache POI) + servlet响应



我想下载一个包含内容的。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的数据是可读的?

您需要为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");

相关内容

  • 没有找到相关文章

最新更新