如何使用 Apache POI 读取特定行? [英] How can I read specific rows with Apache POI?

查看:47
本文介绍了如何使用 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);

请参阅表格的文档.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.

查看文档中关于如何迭代行和单元格的示例.

您可以使用以下内容:

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 为:

You could specify a Row.MissingCellPolicy as:

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
  }
}

这篇关于如何使用 Apache POI 读取特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆