10

I have created a Workbook/Excel in .xlsx format with Java using Apache POI API successfully. My code is as below that is created a file named "RiponAlWasim.xlsx" in D drive:

Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("D:\\RiponAlWasim.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();

When I tried to open "RiponAlWasim.xlsx" it was shown the file is corrupted. What's the wrong?

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
  • 1
    Try `fileOut.flush()` before `close()`. Also, you might need to add at least one worksheet to the workbook, And you should close the workbook before writing – lance-java Oct 15 '15 at 12:25
  • If I close the workbook before writing how will be written on it? There might be thrown "NullPointerException". – Ripon Al Wasim Oct 15 '15 at 13:11
  • Thanks . Yes, the main thing is - it needs to be created at least one worksheet to the workbook. After creating a worksheet it is working. – Ripon Al Wasim Oct 15 '15 at 13:15

4 Answers4

12

It needs to be added at least one sheet to the workbook. So, after creating a worksheet the following code is working well:

Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("Ripon");
FileOutputStream fileOut = new FileOutputStream("D:\\RiponAlWasim.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
0

Reason for corrupted excel: Improper closing of excel due to error inside loop statement

use try-catch block inside loop such that in catch block

  • close the workbook variable
  • close the fileoutput stream variable
  • close the fileinput stream variable

After loop

  • write on workbook using close the fileoutput stream variable
  • close the workbook variable
  • close the fileoutput stream variable
  • close the fileinput stream variable
0

I had a similar issue, in my case I found out that I had used write twice. So if you are getting such error one reason could be that there are multiple writes with same stream.

-1

I added the latest version of xalan (xalan 2.7.1)

Ann
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 04 '21 at 10:10