Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing a poi workbook to output stream is generating weird values

i am aiming to create an Excel file for the user to download via apache poi.

I have this code in my 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");

The problem is that i am getting these weird values:

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

any suggestions?

like image 392
user571099 Avatar asked Jun 28 '12 05:06

user571099


2 Answers

found whats wrong. the HttpServletResponse must first be set before anything else

//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");
like image 173
user571099 Avatar answered Sep 20 '22 12:09

user571099


You need to set cell type for each cell, You can do so using :

cell.setCellType(Cell.CELL_TYPE_STRING );

Check api for more cell types here.

Or You can use DataFormatter for the same.

like image 20
Nandkumar Tekale Avatar answered Sep 18 '22 12:09

Nandkumar Tekale