POI

时间:2017-12-15 07:38:46

标签: java excel apache-poi

我尝试使用Apache POI将2个 List <WebElement> 列表写入Excel文件。但我的方法只保存//column 2值。 //column 1数据未保存在Excel文件中。

请帮我解决此问题。

public void FourthExcel(String classNameOne,String classNameTwo) {

            WebDriverWait wait = new WebDriverWait(driver, 40);
            wait.pollingEvery(2, TimeUnit.SECONDS);

            String filePath = System.getProperty("user.dir");

            //Book one
            XSSFWorkbook workbookOne = new XSSFWorkbook();
            XSSFSheet sheetOne = workbookOne.createSheet("Expenses Sheet");

            CommonClass.sleepTime(3000);

            WebElement expencesTble = driver.findElement(expencesTable);
            wait.until(ExpectedConditions.elementToBeClickable(expencesTble));

            List<WebElement> ColOneList = driver.findElements(By.className(classNameOne));
            List<WebElement> ColTwoList = driver.findElements(By.className(classNameTwo));

            List<Object> ColOneobjectList = Arrays.asList(ColOneList.toArray());
            List<Object> ColTwoobjectList = Arrays.asList(ColTwoList.toArray());

            int ColumnOneSize = ColOneList.size()-1;

            for (int i = 0; i <= ColumnOneSize; i++) {
                out.println("For");
                out.println(ColOneList.get(i).getText());

                //Column 1
                XSSFRow rowOneColZero = sheetOne.createRow(i);
                rowOneColZero.createCell(0).setCellValue(String.valueOf(ColOneobjectList.get(i)));

                //Column 2
                XSSFRow rowOneCOlOne = sheetOne.createRow(i);
                rowOneCOlOne.createCell(1).setCellValue((RichTextString) ColTwoobjectList.get(i));
            }
            try {
                out.println("try");
                FileOutputStream fileOut = new FileOutputStream(filePath + "\\testExcel.xls");
                workbookOne.write(fileOut);
                workbookOne.close();

            } catch (IOException e) {
                out.println(e);

            }
        }

excel文件如下所示:

  

A1数据不会写入excel文件。

enter image description here

1 个答案:

答案 0 :(得分:3)

for循环中覆盖XSSFRow行对象,请按以下方式编写:

    for (int i = 0; i <= ColumnOneSize; i++) {
                    out.println("For");
                    out.println(ColOneList.get(i).getText());

                    //create row
                    XSSFRow row= sheetOne.createRow(i);
                    //to Column 1 
                    row.createCell(0).setCellValue(String.valueOf( ColOneobjectList.get(i)));        
                    //to Column 2
                    row.createCell(1).setCellValue((RichTextString) ColTwoobjectList.get(i));
    }