Search code examples
javaexcelapacheapache-poicorrupt

Excel 2007 file corrupted after being created in Apache POI


I use NetBeans 8. I got problem after compiling this simple code:

package file;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

public class File {

public static void main(String[] args) throws FileNotFoundException, IOException 

{   Workbook wb = new XSSFWorkbook();

    String name = "charlie.xlsx";

    FileOutputStream fileOut = new FileOutputStream(name);

    wb.write(fileOut);
    fileOut.close();

I'm total rookie in Java so basically I rewrote that code from Apache POI documentation, trying to understand how it works. Well - it works fine until I try to open the output file in MS Excel - because then I get a message that file cannot be open cause it's corrupt.

What went wrong?


Solution

  • You need to create a Sheet. Add this to your code and it will work.

    wb.createSheet("Test1");