6

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

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

`...<em>MySheetŒ®üÿ » ÌÁ w dü©ñÒMbP?*+,€%ÿÁƒ„¡"d,,à?à?

有什么建议么?

4

2 回答 2

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");
于 2012-06-28T05:52:51.337 回答
1

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

cell.setCellType(Cell.CELL_TYPE_STRING );

在此处检查 api 以获取更多单元类型。

或者您也可以使用DataFormatter

于 2012-06-28T05:56:51.577 回答