I am writing to data in excel , My process is :
- Get data from website
- Store data into Array
- Write into excel
Problem :
It writes data first time perfectly , But second time when it reaches to Write() function , it fires null pointer exception. I have checked by debug that data is in array but not writing second time.
Code :
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();
}
}
}
First time everything works fine , When it comes second time at wb.write(webdata); , It fires null pointer exception.