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

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

问题描述

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

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

基本上我从变量ArrayList>中读取所有String值并将它们写在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上开发并且总是首先在这里尝试代码,创建的excels很好,我没有任何问题。

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.

有人对此有经验吗?

谢谢。

推荐答案

正如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.

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

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