首页 > 解决方案 > 如何从 JAVA 中的 excel 中获取列值?

问题描述

我如何将每一行和 cloumn 14 值读取到 apache poi 4 中的字符串变量中。

         while (rows.hasNext()) {
                Row currentRow = rows.next();
                System.out.println(currentRow);
                Iterator<Cell> cellsInRow = currentRow.iterator();
                while(cellsInRow.hasNext()) {
                    Cell currentCell = cellsInRow.next();
                    int cellIndex = currentCell.getColumnIndex();
                    int columnidx = 14;
                    String values = currentCell.getStringValue() //how can i get the  value for every row for column 14  
                }
            }

标签: javaapache-poi

解决方案


如果您查看文档,即 的 javadoc Row,您会发现非常方便的getCell(int cellnum)方法:

获取表示给定列(逻辑单元格)的单元格,从 0 开始。如果您要求一个未定义的单元格....您会得到一个null.

这意味着您不应该迭代所有单元格:

while (rows.hasNext()) {
    Row currentRow = rows.next();
    Cell cell14 = currentRow.getCell(13); // 14th cell
    String value = (cell14 == null ? null : cell14.getStringCellValue());
    // use value here
}

不相关,但您不应该使用迭代器while循环。如果您使用 for-each 循环,则代码将更简单,更易于阅读,因此不要:

Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
    Row currentRow = rows.next();

    Iterator<Cell> cellsInRow = currentRow.iterator();
    while (cellsInRow.hasNext()) {
        Cell currentCell = cellsInRow.next();

    }
}

你应该使用:

for (Row currentRow : sheet) {

    for (Cell currentCell : currentRow) {

    }
}

看看代码改进了多少?


推荐阅读