Helping Hands
Helping Hands

Reputation: 5396

Read and write data to excel using POI - It deletes my original data from excel after write new data

I am first reading data from excel and then write in same excel. It works fine first time. Just after data written , It deletes my original data which was there from very beginning.

code is given below :

 public static void main (String args[]) throws Exception {


    //CODE TO REMOVE UNNECESSARY WARNING
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");


    //CALL FIREFOX DRIVER TO OPEN IT
    WebDriver driver = new FirefoxDriver();


    driver.get("https://www.google.co.in/?gfe_rd=cr&ei=VQiAVOeCFavM8gf59IHACg&gws_rd=ssl#q=software+testing");
    java.util.List<WebElement> links = driver.findElements(By.tagName("h3"));
    int sizecount = links.size(); 
    System.out.println(sizecount);

        FileInputStream input = new FileInputStream("D:\\sel.xls");
        int count=0;

        HSSFWorkbook wb = new HSSFWorkbook(input);
        HSSFSheet sh = wb.getSheet("sheet1");
        HSSFRow row = sh.getRow(count);
        String data = row.getCell(0).toString();
        System.out.println(data);

        FileOutputStream webdata = new FileOutputStream ("D:\\sel.xls");

    int inc = 1;
    for(int i=1;i<=links.size()-1;i++)
    {


        HSSFRow row1 = sh.createRow(count);
        row1.createCell(inc).setCellValue(links.get(i).getText());
        count++;


    }
         wb.write(webdata);

Upvotes: 0

Views: 407

Answers (2)

sboda
sboda

Reputation: 363

if you are updating it, you should also update the count variable with the last line of the excel

 int inc = 1;
 count = sh.getPhysicalNumberOfRows();

and do the rest...

Upvotes: 1

Umesh Kumar
Umesh Kumar

Reputation: 1397

you are facing the issue because the index of excel sheets are same when you are writing. First you should check wheater the cell is empty or not then you should write. Or you can first do getrows() or getcolumn() it will give you the size of the rows and columns. once you have the size you can write your data after the that row size and column.

Upvotes: 1

Related Questions