且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Apache POI 读取 Excel .XLSX 时出错

更新时间:2022-05-12 17:14:16

使用上述代码的方法只有一个参数 - FileInputStream.代码片段中的第一行是代码的很大一部分,但也是调用方法的一部分.由于所讨论的方法不了解 Excel 格式,甚至不了解文件扩展名以进行有根据的猜测,因此我决定首先尝试使用 HSSF API 读取 FileInputStream,如下所示:

The method using the above code has a single parameter - FileInputStream. The first line in the code snippet is very much part of the code, but part of the invoking method. Since the method in question did not have knowledge of the Excel format or even a file extension to make an educated guess, I decided that I would first try to read the FileInputStream using HSSF API as below:

Sheet sheet = null;
try {

    POIFSFileSystem poifs = new POIFSFileSystem(inputFS);
    Workbook workbook = new HSSFWorkbook(poifs);
    sheet = workbook.getSheetAt(0);
}
catch (Exception e) {
}

if (sheet == null) {

    try {

        Workbook workbook = new XSSFWorkbook(inputFS);
        sheet = workbook.getSheetAt(0);
    }
    catch (Exception e) {
    }
}

上述代码的问题在于,在第二次尝试通过 XSSF API 打开它时 inputFS 对象的状态是未知的.这产生了读取错误.我用下面的代码替换了上面的代码,它工作正常,问题似乎得到了解决:

The problem with the above code is that the state of the inputFS object during the second attempt of opening it via the XSSF API is unknown. And this yielded a read error. I replaced the above with the following code, which works fine and the issue appears to be resolved:

Sheet sheet = null;
try {

    Workbook workbook = WorkbookFactory.create(inputFS);
    sheet = workbook.getSheetAt(0);
}
catch (Exception e) {
}

我使用 XLS(旧的,二进制)和 XLSX(新的,基于 XML)格式对此进行了测试,并且可以正常工作.感谢大家的帮助和投入!

I tested this with both XLS (older, binary) and XLSX (newer, XML-based) formats and it works. Thanks for everyone's help and input!