Apache POI XSSF 在 Excel 文件中读取

2022-09-03 01:16:27

我只是有一个关于如何使用Apache的XSSF格式读取xlsx文件的简短问题。

现在我的代码看起来像这样:

InputStream fs = new FileInputStream(filename);   // (1)
XSSFWorkbook wb = new XSSFWorkbook(fs);           // (2)
XSSFSheet sheet = wb.getSheetAt(0);               // (3)

...导入所有相关内容。我的问题是,当我点击运行时,它会卡在行(2)上,几乎是无限循环。 只是一个字符串。filename

如果有人能给我一些关于如何解决这个问题的示例代码,我将不胜感激。我现在想要的只是从xlsx文件中读取单个单元格;我对xls文件使用HSSF,没有任何问题。

谢谢你的帮助,安德鲁


答案 1

我希望这将回答您的问题:http://poi.apache.org/spreadsheet/quick-guide.html#ReadWriteWorkbook

简而言之,您的代码应如下所示:

InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);

答案 2
InputStream inp = null;
        try {
            inp = new FileInputStream("E:/sample_poi.xls");

            Workbook wb = WorkbookFactory.create(inp);
            Sheet sheet = wb.getSheetAt(0);
            Header header = sheet.getHeader();

            int rowsCount = sheet.getLastRowNum();
            System.out.println("Total Number of Rows: " + (rowsCount + 1));
            for (int i = 0; i <= rowsCount; i++) {
                Row row = sheet.getRow(i);
                int colCounts = row.getLastCellNum();
                System.out.println("Total Number of Cols: " + colCounts);
                for (int j = 0; j < colCounts; j++) {
                    Cell cell = row.getCell(j);
                    System.out.println("[" + i + "," + j + "]=" + cell.getStringCellValue());
                }
            }

        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                inp.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(FieldController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

推荐