我正在写excel中的数据,我的过程是:
问题:
它首次完美地写入数据,但第二次到达 Write()函数时,它会触发空指针异常。我已通过调试检查数据是否在数组中,但未写入第二次。
代码:
public static void Write_To_Excel() throws IOException
{
int lastrow = 0;
FileInputStream input = new FileInputStream("E:\\Data.xls");
Workbook wb = new HSSFWorkbook(input);
Sheet sh = wb.getSheet("sheet1");
Row row = sh.getRow(0);
lastrow = sh.getLastRowNum();
for(int c=0;c<URLs.size();c++)
{
System.out.println(URLs.get(c).toString());
//driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
driver.get(URLs.get(c).toString());
String Name = driver.findElement(By.id("ProductOverrideName")).getAttribute("value");
String Manufacturer = driver.findElement(By.id("ManufacturerName")).getAttribute("value");
String MPN = driver.findElement(By.id("ProductManufacturerPartNumber")).getAttribute("value");
String Size = driver.findElement(By.id("SizeName")).getAttribute("value");
String Color = driver.findElement(By.id("ColorName")).getAttribute("value");
String Option = driver.findElement(By.id("OptionName")).getAttribute("value");
String Mkeywords = driver.findElement(By.id("ProductOverrideMetaKeywords")).getAttribute("value");
String Mdesc = driver.findElement(By.id("ProductOverrideMetaDescription")).getAttribute("value");
driver.switchTo().frame(0);
String Desc = driver.findElement(By.xpath("/html/body")).getText();
driver.switchTo().defaultContent();
ProductData = new ArrayList<String>();
ProductData.add(Name);
ProductData.add(Manufacturer);
ProductData.add(MPN);
ProductData.add(Size);
ProductData.add(Color);
ProductData.add(Option);
ProductData.add(Mkeywords);
ProductData.add(Mdesc);
ProductData.add(Desc);
lastrow = sh.getLastRowNum();
Row newrow = sh.getRow(lastrow);
newrow = sh.createRow(lastrow+1);
for(int d=0;d<ProductData.size();d++)
{
try{
System.out.println(ProductData.get(d).toString());
Cell cell = newrow.createCell(d);
cell.setCellValue(ProductData.get(d).toString());
}catch(Exception E)
{
E.printStackTrace();
}
}
input.close();
try{
FileOutputStream webdata = new FileOutputStream ("E:\\Data.xls");
wb.write(webdata);
wb.close();
}catch(Exception E)
{
E.printStackTrace();
}
}
}
第一次一切正常,当它第二次出现在 wb.write(webdata); 时,它会触发空指针异常。