Excel 2007 文件在 Apache POI 中创建后损坏

Excel 2007 file corrupted after being created in Apache POI

我使用 NetBeans 8。编译这段简单的代码后我遇到了问题:

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();

我在 Java 中完全是菜鸟,所以基本上我重写了 Apache POI 文档中的代码,试图了解它是如何工作的。好吧 - 它工作正常,直到我尝试在 MS Excel 中打开输出文件 - 因为那时我收到一条消息,说文件无法打开,因为它已损坏。

出了什么问题?

您需要创建一个 Sheet。将此添加到您的代码中,它将起作用。

wb.createSheet("Test1");