11

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?

3
  • 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 Commented Oct 15, 2015 at 12:25
  • If I close the workbook before writing how will be written on it? There might be thrown "NullPointerException". Commented Oct 15, 2015 at 13:11
  • Thanks <Lance Java>. Yes, the main thing is - it needs to be created at least one worksheet to the workbook. After creating a worksheet it is working. Commented Oct 15, 2015 at 13:15

4 Answers 4

13

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Adding the line Sheet sheet1 = wb.createSheet("Ripon"); has solved the problem I faced.
we have flush the fileOut first then we can close the stream
Saved me hours of headache, I totally forgot to close the stream; closing the Workbook is not enough!
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

Comments

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.

Comments

-1

I added the latest version of xalan (xalan 2.7.1)

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.