java - 无法在 Windows 上打开使用 apache poi (Java) 创建的 Excel 文件

标签 java windows excel apache-poi

在我的系统中,我有一个用一些数据创建 excel 的类。

基本上我从变量 ArrayList> 中读取所有字符串值并将它们写入 excel 单元格中。

public void writeData(Data data, int sheetNumber)
        throws EncryptedDocumentException, InvalidFormatException, IOException {
    org.apache.poi.ss.usermodel.Workbook workbook;

    try {
        workbook = WorkbookFactory.create(new File(path));
    } catch (FileNotFoundException e) {
        workbook = new HSSFWorkbook();
    }

    org.apache.poi.ss.usermodel.Sheet sheet;
    try {
        sheet = workbook.createSheet("Sheet" + sheetNumber);
    } catch (IllegalArgumentException e) {
        sheet = workbook.getSheet("Sheet" + sheetNumber);
    }

    int dataListSize = data.getData().size();
    for (int i = 0; i < dataListSize; i++) {
        Row row = sheet.createRow(i);
        int rowSize = data.getData().get(i).size();
        for (int j = 0; j < rowSize; j++) {
            row.createCell(j);
            row.getCell(j).setCellValue(String.valueOf(data.getData().get(i).get(j)));
        }
    }
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(new File(path));
        workbook.write(fos);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        workbook.close();
        if (fos != null) {
            try {

                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

据我所知,代码工作正常,我在 Ubuntu 上开发,总是先在这里尝试代码,创建的 excel 很好,我完全没有问题。

当我将其中一个带到 Windows(XP 和 7,都试过)时,我无法使用 Microsoft Excel 打开它们中的任何一个。

有没有人有这方面的经验?

谢谢。

最佳答案

HSSF 是 Office 97 *.xls 格式。 (代表Horrible Spreadsheet Format。)

} catch (FileNotFoundException e) {
    workbook = new HSSFWorkbook();
}

当您这样做时,您选择了 *.xls 格式。如果你想要 *.xlsx 格式,你需要使用 XSSFWorkbook

https://poi.apache.org/components/spreadsheet/quick-guide.html#NewWorkbook

enter image description here

https://poi.apache.org/components/spreadsheet/

关于java - 无法在 Windows 上打开使用 apache poi (Java) 创建的 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37833979/

相关文章:

javax.net.ssl.SSLException : SSL handshake aborted Connection reset by peer while calling webservice Android

c - POSIX Linux 间隔定时器的可移植解决方案(timer_create、timer_settime...)

c++ - 为什么我不能使用 GetProcAddress 在 DLL 中调用 C++ 静态类工厂方法?

c++ - Windows 上的 block 设备示例

vba - 仅当单元格值实际不同时才触发 'Worksheet_Change' 事件

java - 从数组创建二维矩阵 (java)

java - PMD 违规 : Use explicit scoping instead of the default package private level

java - 如何在 Java 中使用 RFID 读写器

excel - excel中的部分匹配,匹配条件中的多个值以匹配列表

vba - 如何从 Excel VBA 获取总体规划中的 MSP 子项目状态日期