0

Here is my code snippet

  try{

    response.setHeader("Content-Disposition", "attachment;filename=someName.xls");
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("new sheet");

    HSSFRow row = sheet.createRow((short)0);

    HSSFCell cell = row.createCell((short)0);
    cell.setCellValue(1);


    row.createCell((short)1).setCellValue(1.2);
    row.createCell((short)2).setCellValue("Rajesh Kumar ");
    row.createCell((short)3).setCellValue(true);

    FileOutputStream fileOut = new FileOutputStream("C:/Excels/workbook.xls");
    wb.write(fileOut);

    fileOut.close();  
    response.getOutputStream().flush();
    } catch ( Exception ex ) {
          ex.printStackTrace();
    }

The above snippet creates file successfully on hard disk. However whenever the excel sheet is opened it is blank ?

What is the reason ? What can be solution ?

Abhishek Singh
  • 10,243
  • 22
  • 74
  • 108

3 Answers3

2

Have you tried using the response's stream directly:

wb.write(response.getOutputStream());
response.getOutputStream().flush();
Nikhil Talreja
  • 2,754
  • 1
  • 14
  • 20
-1

The documentation for the method says nothing about flushing the stream. Use flush() on fileOut before you close() it.

Deepak Bala
  • 11,095
  • 2
  • 38
  • 49
  • The documentation of FileOutputStream says nothing about it *having* a flush() method of its own. – user207421 Jul 21 '14 at 09:19
  • err... It inherits the `flush()` method from an [OutputStream](http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html). It is unclear if the OP wanted to write to a local stream on the server or a response stream. Either way without flushing the stream, it wont work. – Deepak Bala Jul 21 '14 at 10:27
  • You don't have to flush streams before you close them. Close calls flush. – user207421 Jul 21 '14 at 22:34
-1

HSSFWorkbook.write(FileOutputStream fileOut) not writing anything to the response stream

Correct. It writes to the FileOutputStream you gave it.

If you want it to write to the response output stream, give it the response output stream to write to.

user207421
  • 305,947
  • 44
  • 307
  • 483