将poi工作簿写入输出流正在产生奇怪的值

时间:2012-06-28 05:22:03

标签: servlets apache-poi

我的目标是创建一个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");

问题是我得到了这些奇怪的价值观:

  

`... MySheetŒ®üÿ»Ìw   Dü©ñÒMbP? * +,€%ÿÁƒ“¡“d ,,à·A·

有什么建议吗?

2 个答案:

答案 0 :(得分:7)

发现什么是错的。首先必须先设置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");

答案 1 :(得分:1)

您需要为每个单元格设置单元格类型,您可以使用以下方法设置:

cell.setCellType(Cell.CELL_TYPE_STRING );

检查api以获取更多单元格类型here

或者您可以使用DataFormatter