[英]java.lang.NullPointerException error after reading data from Excel using Apache poi
在下面的以下代碼中,當我嘗試從Excel中讀取數據並將該字段值插入到UI文本框中時,它會拋出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);
我正在獲取Celldata和Celldata1的syst.out,然后在嘗試將Celldata值插入到Email字段后出現此錯誤。
我完整的代碼:
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);
}
在http://gmail.com上,一次沒有輸入密碼的輸入字段。 這就是為什么driver.findElement(By.id("Passwd")).sendKeys(Celldata1);
引起了注意。
填寫電子郵件地址后,可能需要一段時間才能顯示密碼字段。 等待它的最佳方法是這樣的:
WebDriverWait wait = new WebDriverWait(driver, 30); //30s timeout
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Passwd")));
如果您輸入了未知的電子郵件地址(來自Excel文件),則根本不會出現密碼字段。 在這種情況下,請更改測試數據或在代碼中插入一些if
語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.