2013-03-18 59 views
0

我想在Excel中存儲用戶名和密碼,無論我將在使用WebDriver的任何應用程序中輸入什麼內容。我使用TestNg框架和Apache poi將數據寫入Excel。但我得到Null pointer exception。請告訴我如何在Excel中使用WebDriver。如何使用WebDriver和Java使用TestNg框架和Apache poi在Excel中編寫數據

public class Test { 

    private static WebDriver driver; 
    static String username="abc"; 
    static String password="abf123"; 

    public static void main(String args[]) { 
     try { 
      driver.get("any url"); 

      driver.findElement(By.xpath("//*[@id='txtUserName']")).sendKeys(username); 

      driver.findElement(By.xpath("//*[@id='txtPwd']")).sendKeys(password); 

      FileOutputStream fos = new FileOutputStream("Userpass.xls"); 

      HSSFWorkbook workbook = new HSSFWorkbook(); 

      HSSFSheet worksheet = workbook.createSheet("POI WorkSheet"); 

      HSSFRow row1 = worksheet.createRow((short) 0); 

      HSSFCell cell1 = row1.createCell((short) 0); 

      cell1.setCellValue(username); 

      HSSFCell cell2 = row1.createCell((short) 1); 

      cell2.setCellValue(password); 

      workbook.write(fos); 

      fos.close(); 

     } catch (FileNotFoundException e) { 

      e.printStackTrace(); 

     } catch (IOException e) { 

      e.printStackTrace(); 
     } 
    } 
    @Test 
    public void f() { 
    } 
} 
+0

你在哪裏得到空指針? – SpaceCowboy 2013-03-18 10:47:09

+0

當我調試我的程序時,我得到空指針異常here.driver.get(「任何網址」); – sarmila 2013-03-18 10:49:43

+0

也許試試「WebDriver driver = new WebDriver();」不知道這是否會解決問題。 – SpaceCowboy 2013-03-18 10:54:41

回答

1

在你的代碼

HSSFRow row1 = worksheet.createRow((short) 0); 
HSSFCell cell1 = row1.createCell((short) 0); 
cell1.setCellValue(username); 
HSSFCell cell2 = row1.createCell((short) 1); 
cell2.setCellValue(password); 

更換以下幾行

HSSFRow row1 = worksheet.createRow(0); 
row1.createCell(0).setCellValue(new HSSFRichTextString("username")); 
row1.createCell(1).setCellValue(new HSSFRichTextString("password")); 

你會得到所需的輸出。