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

问题描述:

我正在使用Apache POI库,但是我有一些我不想读取的数据-因此,我需要该程序才能从特定的行开始读取文件.

I'm using the Apache POI library, but I have some data that I don't want to be read - So I need the program to start reading the file from a specific row.

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

I want all the data from the cells and rows which comes after row 10, until the document is empty. I have tried with the following code.

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行中所有单元格的数据.

But it will only give me all the data from the cells in row 10.

我期待着您的来信:-).

I'll be looking forward to hear from you :-).

您仅在此处从第11行获取数据:

You're only getting the data from row 11 here:

Row getSchool = firstSheet.getRow(10);

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

返回基于0的逻辑行(非物理). 如果您要求未定义的行,则会得到一个空值.这是为了 例如第4行代表工作表上的第五行.

Returns the logical row (not physical) 0-based. If you ask for a row that is not defined you get a null. This is to say row 4 represents the fifth row on a sheet.

查看文档中有关如何在行和单元格上进行迭代的示例

a>.

您可以使用类似的内容:

You can use something like:

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

for (Row row : firstSheet) {
  for (Cell cell : row) {
     // Do something here
  }
}

如果要迭代访问所有单元格,请检查如何迭代单元格,并控制缺少/空白的单元格.

If you want to iterate over all cells in a row check how to Iterate over cells, with control of missing / blank cells.

CellIterator将仅返回文件中定义的单元格,大部分是带有值或样式的单元格,但这取决于Excel.

The CellIterator will only return the cells defined in the file, which is largely those with values or stylings, but it depends on 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
  }
}