简体   繁体   English

使用POI读取和写入数据到excel-写入新数据后,它会从excel中删除我的原始数据

[英]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. 我首先从excel读取数据,然后再写入相同的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);

you are facing the issue because the index of excel sheets are same when you are writing. 您正面临这个问题,因为在编写时excel工作表的索引是相同的。 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. 或者,您可以先执行getrows()或getcolumn(),它将为您提供行和列的大小。 once you have the size you can write your data after the that row size and column. 一旦有了大小,就可以在该行大小和列之后写入数据。

if you are updating it, you should also update the count variable with the last line of the excel 如果要更新它,还应该用excel的最后一行更新count变量

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

and do the rest... 剩下的...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM