无法调用"org.apache.poi.ss.usermodel.Cell.getStringCellValue()",因为 org.apache.poi.ss.usermodel.Row.getCe



我正在访问我的Excel工作表数据,我能够获得我的输出,但与此同时,我得到了一个错误:

无法调用"org.apache.poi.ss.usermodel.Cell.getStringCellValue(("因为org.apache.poi.ss.usermodel.Row.getCell(int(的返回值为null

我在这行代码上得到了这个错误:

if(r.getCell(column).getStringCellValue().equalsIgnoreCase("Login ID")

这是我的全部代码:

package Exceltwo.guruExcel;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class excelDataProvider {
//Identify Testcases column by scanning the entire 1st row
//once column is identified then scan entire testcase column to identify purchase testcase row
//after you grab purchase testcase row = pull all the data of that row and feed into test
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("C:\Users\mimo\Desktop\workbookexample.xlsx");
XSSFWorkbook workbook=new XSSFWorkbook(fis);
int sheets = workbook.getNumberOfSheets();
for (int i = 0; i < sheets; i++)
{
if (workbook.getSheetName(i).equalsIgnoreCase("Sheet1"))
{
XSSFSheet sheet = workbook.getSheetAt(i);
//Identify Testcases column by scanning the entire 1st row
Iterator<Row> rows = sheet.iterator();  // sheet is collection of rows
Row firstrow = rows.next();
Iterator<Cell> ce = firstrow.cellIterator();  // row is collection of cells
int k = 0;
int column = 0;
while (ce.hasNext())
{
Cell value = ce.next();

if (value.getStringCellValue().equalsIgnoreCase("Testcase"))
{
column = k;
}
k++;
}
System.out.println(column);
// once column is identified then scan entire testcase column to identify purchase testcase row
while (rows.hasNext())
{
Row r = rows.next();
if (r.getCell(column).getStringCellValue().equalsIgnoreCase("Login ID"))
{ 
// after you grab purchase testcase row = pull all the data of that row and feed into test
Iterator<Cell> cv = r.cellIterator();
while (cv.hasNext())
{
Cell c = cv.next();
System.out.println(c);
}
}
}
}
}
// TODO Auto-generated method stub
}

Excel屏幕截图

控制台屏幕截图

正如注释中所指出的,r.getCell(column)可以返回null。

另一个选项(除了检查null之外(是使用CellUtil.getCell(r, column),它不会返回null,因为如果它不存在,它会创建单元格。

请参阅https://poi.apache.org/apidocs/dev/org/apache/poi/ss/util/CellUtil.html#getCell-org.apache.poi.ss.usermodel.Row-int-

**Add one more if block for checking whether the cell is null or not then it will execute without any error...**
while(rows.hasNext())
{
Row r=rows.next();
if(r.getCell(column)!=null)
{                    
if(r.getCell(column).getStringCellValue().equalsIgnoreCase("Login ID"))
{
Iterator<Cell> cv=r.cellIterator();
while(cv.hasNext())
{
Cell c = cv.next();
System.out.println(c);
}
}
}
}

更改此

while (cv.hasNext())

到这个

while (cv.hasNext() == true)

这是因为,在给定单元格的下一个/下一个单元格之后没有可用值。

最新更新