:)我正在尝试使用Selenium-WebDriver和Java将Web表数据写入excel文件。通过以下代码,我只能打印excel中的最后一列数据,但不能打印整个webtable数据。你能帮帮我吗.....
import java.util.*;
import java.lang.*;
import java.io.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebTableTOSpreedsheet
{
public static void main(String[] args) throws IOException
{
System.out.println("Hello Dear.....");
System.out.println();
WebDriver wb = new FirefoxDriver();
wb.navigate().to("http://www.w3schools.com/html/html_tables.asp");
wb.manage().window().maximize();
System.out.println(wb.getTitle() +" - WebPage has been launched");
List<WebElement> irows = wb.findElements(By.xpath("//*[@id='main']/table[1]/tbody/tr"));
int iRowsCount = irows.size();
List<WebElement> icols = wb.findElements(By.xpath("//*[@id='main']/table[1]/tbody/tr[1]/th"));
int iColsCount = icols.size();
System.out.println("Selected web table has " +iRowsCount+ " Rows and " +iColsCount+ " Columns");
System.out.println();
FileOutputStream fos = new FileOutputStream("D://Software//AutomationPractise//WebTableTOSpreedsheet.xlsx");
XSSFWorkbook wkb = new XSSFWorkbook();
XSSFSheet sheet1 = wkb.createSheet("DataStorage");
for (int i=1;i<=iRowsCount;i++)
{
for (int j=1; j<=iColsCount;j++)
{
if (i==1)
{
WebElement val= wb.findElement(By.xpath("//*[@id='main']/table[1]/tbody/tr["+i+"]/th["+j+"]"));
String a = val.getText();
System.out.print(a);
XSSFRow excelRow = sheet1.createRow(i);
XSSFCell excelCell = excelRow.createCell(j);
excelCell.setCellType(XSSFCell.CELL_TYPE_STRING);
excelCell.setCellValue(a);
//wkb.write(fos);
}
else
{
WebElement val= wb.findElement(By.xpath("//*[@id='main']/table[1]/tbody/tr["+i+"]/td["+j+"]"));
String a = val.getText();
System.out.print(a);
XSSFRow excelRow = sheet1.createRow(i);
XSSFCell excelCell = excelRow.createCell(j);
excelCell.setCellType(XSSFCell.CELL_TYPE_STRING);
excelCell.setCellValue(a);
//wkb.write(fos);
}
}
System.out.println();
}
fos.flush();
wkb.write(fos);
fos.close();
}
}
答案 0 :(得分:0)
您正在为s:label key="gettext('*')"
循环中的每个单元格创建新的空行。移动for (int j=1; j<=iColsCount;j++)
以循环迭代XSSFRow excelRow = sheet1.createRow(i);
。
i
对于其他人,我必须将其添加到我的代码中才能正确执行:
for (int i = 1; i <= iRowsCount; i++) {
XSSFRow excelRow = sheet1.createRow(i);
for (int j = 1; j <= iColsCount; j++) {