无法在 Windows 上打开使用 apache poi (Java) 创建的 Excel 文件 [英] Excel file created with apache poi (Java) can't be opened on Windows

查看:35
本文介绍了无法在 Windows 上打开使用 apache poi (Java) 创建的 Excel 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my system, I have a class that creates an excel with some data.

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

Basically I read all String values from a variable ArrayList> and write them in excel cells.

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 很好,我完全没有问题.

The code works fine as far as I know, I develop on Ubuntu and always try the code here first, the created excels are fine, and I have no problem at all.

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

When I take one of these to Windows (XP and 7, tried on both), I can't open any of them using Microsoft Excel.

有人有这方面的经验吗?

Does anyone have any experience with this?

谢谢.

推荐答案

正如 Axel 所说,问题在于文件扩展名.

As Axel mentioned, the problem was the file extension.

我可以在 Ubuntu(14.04 和 16.04)中打开以这种方式创建的文件,但不能在 Windows(7、8 和 10)中打开.

I can open the files created this way in Ubuntu (Both 14.04 and 16.04), but not in Windows (7, 8 and 10).

解决方案是使用 .xls 扩展名而不是 .xlsx,这样我就可以在任何操作系统中打开和使用文件.

The solution is to use the .xls extension and NOT .xlsx, that way I can open and use the files in any OS.

这篇关于无法在 Windows 上打开使用 apache poi (Java) 创建的 Excel 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆