如何使用Apache POI读取特定行?

7

我正在使用Apache POI库,但是有些数据我不希望被读取 - 因此我需要程序从特定行开始读取文件。

我想要从第10行之后的所有单元格和行中获取的数据,直到文档为空。我已尝试使用以下代码。

Workbook workbook = new XSSFWorkbook(inputStream);
    Sheet firstSheet = workbook.getSheetAt(0);

    Iterator<Row> iterator = firstSheet.iterator();
    Row getSchool = firstSheet.getRow(10);

    Iterator<Cell> cellIterator = getSchool.cellIterator();

    while (iterator.hasNext())
    {
        while (cellIterator.hasNext())
        {
         ...
        }
    }

但是它只会给我第10行单元格中的所有数据。

我期待您的回复 :-).

2个回答

15

这里只获取了第11行的数据:

Row getSchool = firstSheet.getRow(10);

请参考Sheet.getRow(int rownum)的文档。

返回基于0的逻辑行(非物理行)。如果请求未定义的行,则会返回null。这意味着第四行表示工作表上的第五行。

请查看文档中的示例,了解如何迭代行和单元格

您可以使用类似以下的代码:

Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);

for (Row row : firstSheet) {
  for (Cell cell : row) {
     // Do something here
  }
}
如果您想迭代遍历一行中的所有单元格,请查看如何使用控制缺失/空单元格的迭代方法CellIterator仅返回文件中定义的单元格,通常是带有值或样式的单元格,但这取决于Excel本身。
您可以将Row.MissingCellPolicy指定为:
Row.getCell(int, MissingCellPolicy)

这里有一个例子:

int lastColumn = Math.max(row.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT);

for (int cn = 0; cn < lastColumn; cn++) {
  Cell c = row.getCell(cn, Row.RETURN_BLANK_AS_NULL);
  if (c == null) {
    // The spreadsheet is empty in this cell
  } else {
    // Do something useful with the cell's contents
  }
}

1
参考以下内容:
        String fileName = "D:\\TestScripts.xls"; // file
        POIFSFileSystem fileSystem = new POIFSFileSystem(new FileInputStream(fileName));
        HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
    //  HSSFSheet sheet = workbook.getSheetAt(0); //Get first Excel Sheet
        HSSFSheet sheet = workbook.getSheet("SheetName"); //Get data as per sheet name
        for (Row row : sheet) { // For each Row.
              Cell cell = row.getCell(0); // Get the Cell at the Index / Column you want.
              if(cell.getStringCellValue().equalsIgnoreCase("test")) {
                  System.out.println(cell.getRow().getLastCellNum());
                  for(int i=0;i<=cell.getRow().getLastCellNum()-1;i++) {
                      System.out.println(cell.getRow().getCell(i));
                  }
              }
           }

如果您不需要任何特定的列数据,请删除以下条件。
 if(cell.getStringCellValue().equalsIgnoreCase("test"))

注意:您需要根据表格数据标题更改上述代码中的test为您的列名,例如id、name。请保留HTML标签。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接