我想将用户名和密码存储在 Excel 中,无论我在使用 WebDriver 的任何应用程序中输入什么内容。我正在使用 TestNG 框架和 Apache POI 将数据写入 Excel。但我收到空指针异常
。请告诉我如何将 WebDriver 与 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() {
}
}
最佳答案
替换代码中的以下行
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"));
您将获得所需的输出。
关于java - 如何使用 TestNG 框架和 Apache POI 通过 WebDriver 使用 Java 在 Excel 中写入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15474598/