通过传递单元格地址读取 POI 中的一系列值

问题描述 投票:0回答:1

我正在尝试使用 Apache POI 使用 AreaReference API 读取 Excel 文件中的一系列单元格值。 似乎遇到了运行时异常。

Click here to see the image representation

我尝试使用下面的示例代码,

FileInputStream  fis =new FileInputStream(new File("testRange.xlsx")); 
XSSFWorkbook workbook=new XSSFWorkbook(fis);   
XSSFSheet sheet=workbook.getSheetAt(0);  
AreaReference areaReference = new AreaReference(sheet.getSheetName() + "!B2:K2", SpreadsheetVersion.EXCEL2007);
CellReference[] crefs = (CellReference[]) areaReference.getAllReferencedCells();
for (int i=0; i<crefs.length; i++) {
    XSSFSheet s = workbook.getSheet(crefs[i].getSheetName());
    XSSFRow r = s.getRow(crefs[i].getRow());
    XSSFCell c = r.getCell(crefs[i].getCol());
}

任何帮助表示赞赏。谢谢。

java apache-poi
1个回答
0
投票

尝试使用下面的代码,

fis=new FileInputStream(new File("testRange.xlsx"));            XSSFWorkbook workbook=new XSSFWorkbook(fis);                XSSFSheet sheet=workbook.getSheetAt(0);  
                        CellReference ref = new CellReference("B2");            XSSFRow row = sheet.getRow(ref.getRow());           XSSFRow nextRow = sheet.getRow(row.getRowNum() + 1);
             if (row != null) {
                List<String> categoryData =  collectData(row);
                System.out.println("Category Data");
                categoryData.forEach(System.out::println);
             }
             
             if (nextRow != null) {
                 List<String> values =  collectData(nextRow);
                 System.out.println("Values");
                 values.forEach(System.out::println);
             }

             private static List<String> collectData(XSSFRow row) {         List<String> data = new ArrayList<>();      final DataFormatter df = new DataFormatter();       for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
                XSSFCell cell = row.getCell(i);
                if(cell != null) {
                    data.add(df.formatCellValue(cell));
                }
            }       return data;    }

    though not exactly what i was looking for, Still solves the problem, Is there a more elegant solution?
© www.soinside.com 2019 - 2024. All rights reserved.