Java – xlsx file created in the java code is not opening in ms excel, says the file format or file extension is not valid

apache-poiexceljava

I have a java code to create a excel file and it works fine for the extensions .xls and .xlsx I'm able to open .xls file but unable to open the file extension .xlsx in ms excel and it says Excel cannot open the 'sample.xlsx' file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

Below is my java code I used.

HSSFWorkbook workBook = new HSSFWorkbook();
String file = "D:/sample.xlsx";
FileOutputStream fos = new FileOutputStream(file);
workBook.write(fos);
fos.flush();   

I have gone thru the below link which looked like having similar issue but I didn't find the answer so raised here as new question.
File Excel From Apache POI Cant Open by Ms Excel (corrupt)

Best Answer

If you're attempting to create an Excel file with the .xlsx extension, you need to use the XSSFWorkbook. I suggest reading this to understand the difference between the XSSFWorkbook and the HSSFWorkbook objects.

Further, you can use the documentation here to figure out how to make a new Excel file using Apache POI.

Essentially, you'll be doing this:

Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.close();
Related Topic