想要使用for循环在xlsx文件中写入文本

时间:2019-05-14 09:56:23

标签: java apache-poi

我想将变量b的文本存储到Excel工作表中。

 @Test
public void Test() throws IOException, InterruptedException {
    File src =new File("F:\\text.xlsx");
    System.setProperty("webdriver.chrome.driver","C:\\ChromeDriver\\chromedriver.exe");

        ChromeOptions options = new ChromeOptions();
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);       
        driver.get("https://www.printvenue.com/c/pens");
        System.out.println("Successfully opened Category");
        driver.manage().window().maximize();

      // Write data in the excel.

         List<WebElement> links = 
    driver.findElements(By.xpath("//span[@class = 'buynow-yellow']//a"));
         //System.out.println("Total " + links.size() +" products avilable 
 on Home Page.");

         System.out.println("Total " + links.size() +" product category avilable under above HomePage Link.");
         for( int j = 1; j <= links.size(); j++)
         {

             //The stop below is necessary to store all links in a list to access later.  
             try {
            links = driver.findElements(By.xpath("//span[@class = 'buynow-yellow']//a")); 
            System.out.println(links.get(j).getAttribute("href"));
            System.out.println("Product Index No: "+j);
            links.get(j).click();
            Thread.sleep(2000);
            driver.findElement(By.xpath("//*[@id=\"template_container\"]/div[1]/div/ul/li/img[3]")).click();
            b =driver.findElement(By.className("editor_product_name")).getText();
            System.out.println(b);

            FileInputStream finput = new FileInputStream(src);
            XSSFWorkbook Workbook = new XSSFWorkbook(finput);
            XSSFSheet sheet = Workbook.createSheet("ABC");

            for(int i=0; i<=sheet.getLastRowNum(); i++)
            {

            cell.setCellType(cell.CELL_TYPE_STRING);
            sheet.getRow(i).createCell(0).setCellValue(b);

           FileOutputStream foutput=new FileOutputStream(src);


           Workbook.write(foutput);

            foutput.close();
            }
             driver.navigate().back();
             Thread.sleep(1000);
             driver.navigate().back();
             Thread.sleep(1000);
             driver.navigate().back();
             Thread.sleep(1000);
             driver.navigate().back();


             }
             catch(Exception e) {
                System.out.println("Note: Not reached till Add to cart/Product is sold out.\r\n");
                Thread.sleep(7000);
                driver.navigate().back();
                driver.navigate().back();


             }

         }

 }

我已经在类中将b声明为静态字符串变量,并且      希望每次在exel文件的下一行中存储变量b的文本      但这不会在运行此代码后更新exel表。所以      请提出解决方案。

0 个答案:

没有答案