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

标签 java excel apache apache-poi

我正在使用 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 行单元格中的所有数据。

我期待收到您的来信 :-)。

最佳答案

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

Row getSchool = firstSheet.getRow(10);

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

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.

查看文档中的示例,了解如何 Iterate over rows and cells .

你可以使用类似的东西:

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

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

如果您想遍历一行中的所有单元格,请查看如何 Iterate over cells, with control of missing / blank cells .

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

关于java - 如何使用 Apache POI 读取特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37027731/

相关文章:

java - 创建.htaccess

java - 图着色算法 : typical scheduling problem

excel - 如何根据表格中的选项卡名称隐藏 Excel 工作簿中的工作表

python - 使用 xlrd,如何替换丢失/NaN 单元格

javascript - 无论我尝试什么,请求的资源错误上均不存在 'Access-Control-Allow-Origin' header

apache - 迁移到 https(网站 + KeyCDN)后 htaccess 出现问题

java - 如何配置 Jackson 以反序列化包含在基类上使用 @JsonTypeInfo 和 JsonSubTypes 注释的命名类型的列表?

java - 使用 JavaScript 和 JSP 使用动态信息填充 Google Analytics 标签

java - 系统剪贴板操作的右键菜单项

c# - 如何在不安装 Microsoft Office 的情况下在 C# 中创建 Excel(.XLS 和 .XLSX)文件?