写一个POI工作簿输出流产生奇怪的值(writing a poi workbook to outpu

2019-09-18 16:17发布

我的目标创建一个Excel文件,为用户通过Apache POI下载。

我有我的servlet的代码:

protected void doGet(HttpServletRequest request, 
              HttpServletResponse response) throws ServletException, IOException 
      {

            // create a workbook , worksheet
            Workbook wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("MySheet");
            CreationHelper createHelper = wb.getCreationHelper();

            // Create a row and put some cells in it. Rows are 0 based.
            Row row = sheet.createRow((short)0);
            Cell cell = row.createCell(0);
            cell.setCellValue(1);
            row.createCell(1).setCellValue(1.2);
            row.createCell(2).setCellValue( createHelper.createRichTextString("This is a string") );
            row.createCell(3).setCellValue(true);

            //write workbook to outputstream
            ServletOutputStream out = response.getOutputStream();
            wb.write(out);
            out.flush();
            out.close();

            //offer the user the option of opening or downloading the resulting Excel file
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=MyExcel.xls");

问题是,我得到这些奇怪的值:

`...MySheetOe®uy»IAW¯¯©nOMbP就够了吗? * +,€%yAƒ “¡” d ,,你?阿?

有什么建议么?

Answer 1:

发现什么是错。 HttpServletResponse的首先必须先天下之忧设置

//offer the user the option of opening or downloading the resulting Excel file
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=MyExcel.xls");


Answer 2:

您需要设置单元格类型的每个单元,你可以这样做使用:

cell.setCellType(Cell.CELL_TYPE_STRING );

检查API的多种细胞类型在这里 。

或者您可以使用DataFormatter的一样。



文章来源: writing a poi workbook to output stream is generating weird values