簡體   English   中英

無法在 Windows 上打開使用 apache poi (Java) 創建的 Excel 文件

[英]Excel file created with apache poi (Java) can't be opened on Windows

在我的系統中,我有一個類可以用一些數據創建一個 excel。

基本上我從變量 ArrayList> 中讀取所有 String 值並將它們寫入 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 打開其中任何一個。

有人對這個有經驗么?

謝謝你。

正如 Axel 所提到的,問題在於文件擴展名。

我可以在 Ubuntu(14.04 和 16.04)中打開以這種方式創建的文件,但不能在 Windows(7、8 和 10)中打開。

解決方案是使用.xls擴展名而不是.xlsx ,這樣我就可以在任何操作系統中打開和使用文件。

HSSF 是 Office 97 *.xls 格式。 (它代表H orrible S pread s heet F格式。)

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

當您這樣做時,您選擇了 *.xls 格式。 如果需要 *.xlsx 格式,則需要使用XSSFWorkbook

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

在此處輸入圖片說明

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM