使用Apache poi从Excel读取数据后发生java.lang.NullPointerException错误
问题描述:
在我尝试将该字段值插入到UI文本框中时,在从Excel中读取数据之后的以下代码中,它将引发错误为java.lang.nullpointerexception
。使用Apache poi从Excel读取数据后发生java.lang.NullPointerException错误
在下面的代码中,当我尝试通过保留syst.out读取Excel中的值时,它向我显示正确的值。
我在这段代码
Cell=ExcelWSheet.getRow(1).getCell(0);
Cell1=ExcelWSheet.getRow(1).getCell(1);
String Celldata=Cell.getStringCellValue();
String Celldata1=Cell1.getStringCellValue();
System.out.println(Celldata);
System.out.println(Celldata1);
System.out.println("username value");
Thread.sleep(2000);
****driver.findElement(By.id("Email")).sendKeys(Celldata);
我正在syst.out为Celldata和Celldata1,面向然后当我试图插入Celldata值到电子邮件领域正在此错误后问题。
我的完整代码:
public class NewTest {
public WebDriver driver;
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFCell Cell1;
private static XSSFRow Row;
@Test
public void f() throws Exception {
// This method is to set the file path and open the excel file
try{
WebDriver driver=new FirefoxDriver();
//driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://gmail.com");
Thread.sleep(3000);
FileInputStream Excelfile=new FileInputStream("D:\\TestData\\Login.xlsx");
ExcelWBook=new XSSFWorkbook(Excelfile);
ExcelWSheet=ExcelWBook.getSheet("Sheet1");
} catch (Exception e){
throw(e);
}
// This code is used to read data from excel file
try{
Cell=ExcelWSheet.getRow(1).getCell(0);
Cell1=ExcelWSheet.getRow(1).getCell(1);
String Celldata=Cell.getStringCellValue();
String Celldata1=Cell1.getStringCellValue();
System.out.println(Celldata);
System.out.println(Celldata1);
System.out.println("username value");
Thread.sleep(2000);
****driver.findElement(By.id("Email")).sendKeys(Celldata);
driver.findElement(By.id("next")).click();
driver.findElement(By.id("Passwd")).sendKeys(Celldata1);****
}catch (Exception e){
throw(e);
}
// This code is used to write data to the excel sheet
try{
Row=ExcelWSheet.getRow(1);
Cell=Row.getCell(2,Row.RETURN_BLANK_AS_NULL);
if(Cell==null){
Cell=Row.createCell(2);
Cell.setCellValue("Pass");
FileOutputStream fileout=new FileOutputStream("Login.xlsx");
ExcelWBook.write(fileout);
fileout.flush();
fileout.close();
}}catch(Exception e){
throw(e);
}
答
在密码输入字段不存在一次。这就是为什么 driver.findElement(By.id("Passwd")).sendKeys(Celldata1);
引起的兴趣。
填写电子邮件地址后,可能需要一段时间才能显示密码字段。等待它最好的办法是这样的:
WebDriverWait wait = new WebDriverWait(driver, 30); //30s timeout
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Passwd")));
如果你已经进入一个未知的电子邮件地址(Excel文件中)的口令字段不会出现在所有。在这种情况下,更改测试数据或在代码中插入一些if
语句。