且构网

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

使用 Java 读取 Excel 工作表时出错

更新时间:2022-11-30 15:30:30

您的代码目前明确要求 HSSF,因此只能使用较旧的 .xls(二进制)文件.

Your code as it stands explicitly requests HSSF, so will only work with the older .xls (binary) files.

如果需要,您可以让 POI 自动检测您拥有的文件类型,并为您的情况选择合适的 HSSF 或 XSSF 之一.但是,要做到这一点,您需要稍微更改代码,并使用接口而不是具体的类(因此无论您获得的是 HSSF 还是 XSSF 对象,您的代码都可以工作)

If you want, you can ask POI to auto-detect which file type you have, and pick the appropriate one of HSSF or XSSF for your case. However, to do that you need to change your code slightly, and use interfaces rather than concrete classes (so your code works whether you get a HSSF or XSSF object)

POI 网站有一个进行这些更改的指南,应该会指导您完成.

The POI website has a guide to making these changes which should guide you through.

例如,当您按照此操作时,您的前几行是:

As an example, when you follow this, your first few lines which were:

    HSSFWorkbook myWorkBook = new HSSFWorkbook(new POIFSFileSystem(new FileInputStream("E:/Project/SpringHibernet/MultiplexTicketBookingNew/web/excelSheets/Country.xlsx")));
    HSSFSheet mySheet = myWorkBook.getSheetAt(0);
    Iterator rowIter = mySheet.rowIterator();
    System.out.println(mySheet.getRow(1).getCell(0));

将成为新系统:

    Workbook wb = WorkbookFactory.create(new File("/path/to/your/excel/file"));
    Sheet mySheet = wb.getSheetAt(0);
    Iterator<Row> rowIter = mySheet.rowIterator();
    System.out.println(mySheet.getRow(1).getCell(0));

这将适用于 .xls 和 .xlsx 文件

This will then work for both .xls and .xlsx files