Writing a poi workbook to output a stream produces strange values

I am trying to create an excel file to be downloaded by a user through 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 get these strange values:

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

any suggestions?

+6
source share
2 answers

found what is wrong. 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"); 
+7
source

You need to set the cell type for each cell, you can do this using:

 cell.setCellType(Cell.CELL_TYPE_STRING ); 

Check api for more cell types here .

Or you can use a DataFormatter for this.

+1
source

Source: https://habr.com/ru/post/919210/


All Articles