Java 在Selenium WebDriver中读写excel
我是Selenium WebDriver的新手,还在学习。我只想从excel中读取数据,并将数据写入同一个excel表或不同的excel表中 用于登录的用户名和密码以两列形式存储在excel工作表中。我想从excel工作表中读取用户名/密码。如果它是一个有效的用户名/pwd,我只想在新列中写“通过”,否则我需要写为“失败” 我的代码可以成功地从excel工作表中读取数据。然而,我一直在用excel表格写数据Java 在Selenium WebDriver中读写excel,java,excel,selenium,selenium-webdriver,Java,Excel,Selenium,Selenium Webdriver,我是Selenium WebDriver的新手,还在学习。我只想从excel中读取数据,并将数据写入同一个excel表或不同的excel表中 用于登录的用户名和密码以两列形式存储在excel工作表中。我想从excel工作表中读取用户名/密码。如果它是一个有效的用户名/pwd,我只想在新列中写“通过”,否则我需要写为“失败” 我的代码可以成功地从excel工作表中读取数据。然而,我一直在用excel表格写数据 感谢阅读并站出来澄清我的疑问 考虑使用ApachePOI来读写excel。可能您可以编写
感谢阅读并站出来澄清我的疑问 考虑使用ApachePOI来读写excel。可能您可以编写一个简单的
Util
类来读取和写入excel
Sheet sheet = wb.createSheet("Selenium Results");
Row titleRow = sheet.createRow(0)
row = sheet.createRow(11);
cell = row.createCell(2);
cell.setCellValue("Total cost of loan");
参考此
在您的情况下,您可能只需要迭代现有的excel,然后进行读/写。以下使用Apache POI的Selenium Java代码应该可以工作:
public String readDataFromExcel(int rowcount,int columncount,String filepath,String Sheetname )
{
String data=null;
try
{
FileInputStream input= new FileInputStream(filepath);
XSSFWorkbook wb=new XSSFWorkbook(input);
XSSFSheet sh=wb.getSheet(Sheetname);
XSSFRow row=sh.getRow(rowcount);
row.getCell(columncount).toString();
}
catch(Exception e)
{
System.out.println(e);
}
return data;
}
public void writeDataFromExcel(int rowcount,int columncount,String filepath,String Sheetname,String value)
{
try
{
FileInputStream input=new FileInputStream(filepath);
XSSFWorkbook wb=new XSSFWorkbook(input);
XSSFSheet sh=wb.getSheet(Sheetname);
XSSFRow row=sh.getRow(rowcount);
FileOutputStream webdata=new FileOutputStream(filepath);
row.createCell(columncount).setCellValue(value);
wb.write(webdata);
}
catch(Exception e)
{
}
}
公共类Xls\U读卡器
{
公共字符串路径=”;
私人工作簿=空;
私有表=空;
公共Xls_读取器(字符串文件路径)
{
路径=文件路径;
工作簿=获取工作簿(路径);
工作表=工作簿。getSheetAt(0);
}
/**
*此函数用于返回excel文件的工作簿对象
*@param path是文件系统中文件的位置
*@xssf工作簿类型的返回对象
*/
公共工作簿getWorkBook(字符串路径)
{
工作簿=空;
文件=新文件(路径);
if(file.exists())
{
尝试
{
FileInputStream输入=新的FileInputStream(路径);
字符串扩展名=FilenameUtils.getExtension(路径);
工作簿=extension.equalsIgnoreCase(“xls”)?新的HSSF工作簿(输入):新的XSSF工作簿(输入);
input.close();
}
捕获(IOE异常)
{
抛出新的TARuntimeException(String.format(“打开文件(%s)”时出现问题,路径),e;
}
}
其他的
{
抛出新的NotFoundException(String.format(“文件(%s)不存在..!!”,路径));
}
返回工作簿;
}
/**
*根据图纸名称,它返回图纸对象
*@param sheetName是图纸的名称
*@return if sheet exist返回XSSFSheet对象,否则返回null。
*/
公共工作表getSheet(字符串sheetName)
{
if(workbook.getSheetName(workbook.getSheetIndex(sheet)).equals(sheetName))
{
报税表;
}
if(sheetName==null | | sheetName.isEmpty())
{
}
其他的
{
int index=workbook.getSheetIndex(sheetName);
如果(索引==-1)
{
抛出新的NotFoundException(String.format(“在Excel工作簿(%s)中找不到工作表(%s)”,工作表名称,路径));
}
其他的
{
工作表=工作簿。getSheetAt(索引);
}
}
报税表;
}
/**
*根据索引,它返回图纸对象
*@param index-是工作表的索引
*@return if sheet exist返回XSSFSheet对象,否则返回null。
*/
公共图纸getSheetAt(内部索引)
{
如果(索引=0 | |行数>=0)
{
尝试
{
sheet=getSheet(sheetName);
Row Row=sheet.getRow(行号);
Cell Cell=row.getCell(columnNumber);
celldata=getCellContentAsString(单元格);
}
捕获(NullPointerException e)
{
TALogger.logError(“读取单元格时获取NullPointerException=>Sheet_Name=“+sheetName+”column=“+columnNumber+”rownumber=“+rownumber”);
返回“”;
}
捕获(例外情况除外)
{
TALogger.logError(“读取单元格时获取异常=>Sheet_Name=“+sheetName+”column=“+columnNumber+”rownumber=“+rownumber,ex”);
返回“”;
}
}
其他的
{
抛出新的TARuntimeException(“无效索引..!!rowIndex=“+rowNumber+”columnIndex=“+columnNumber”);
}
返回数据;
}
/**
*此函数以字符串形式返回单元格内容
*@param sheetName
*@param columnName
*@param行数
*@return以字符串形式返回单元格内容
*/
公共字符串getCellData(字符串sheetName、int rowNumber、字符串columnName)
{
字符串celldata=“”;
sheet=getSheet(sheetName);
int columnNumber=getColumnNumber(0,columnName);
如果(列数>=0 | |行数>=0)
{
尝试
{
Row Row=sheet.getRow(行号);
Cell Cell=row.getCell(columnNumber);
celldata=getCellContentAsString(单元格);
}
捕获(NullPointerException e)
{
TALogger.logError(“读取单元格时获取NullPointerException=>Sheet_Name=“+sheetName+”column=“+columnNumber+”rownumber=“+rownumber”);
返回“”;
}
捕获(例外情况除外)
{
//此日志错误应在此处。如果单元格为空,有时在读取单元格数据时会出现异常。
TALogger.logError(“读取单元格时获取异常=>Sheet_Name=“+sheetName+”column=“+columnNumber+”rownumber=“+rownumber,ex”);
返回“”;
}
}
其他的
{
抛出新的TARuntimeException(“无效索引..!!rowIndex=“+rowNumber+”columnIndex=“+c
public class Xls_Reader
{
public String path="";
private Workbook workbook=null;
private Sheet sheet=null;
public Xls_Reader(String filePath)
{
path=filePath;
workbook=getWorkBook(path);
sheet=workbook.getSheetAt(0);
}
/**
* This function returns workbook object of excel file
* @param path is location of file in file System
* @return object of Type XSSFWorkbook
*/
public Workbook getWorkBook(String path)
{
Workbook workbook=null;
File file=new File(path);
if(file.exists())
{
try
{
FileInputStream input= new FileInputStream(path);
String extension=FilenameUtils.getExtension(path);
workbook= extension.equalsIgnoreCase("xls")?new HSSFWorkbook(input):new XSSFWorkbook(input);
input.close();
}
catch (IOException e)
{
throw new TARuntimeException(String.format("Problem While opening the file(%s)", path), e);
}
}
else
{
throw new NotFoundException(String.format("File(%s) is not exist..!!", path));
}
return workbook;
}
/**
* Depending upon sheet name it returns the sheet object
* @param sheetName is name of sheet
* @return if sheet exist returns XSSFSheet object else returns null.
*/
public Sheet getSheet(String sheetName)
{
if(workbook.getSheetName(workbook.getSheetIndex(sheet)).equals(sheetName))
{
return sheet;
}
if(sheetName==null || sheetName.isEmpty())
{
}
else
{
int index=workbook.getSheetIndex(sheetName);
if(index==-1)
{
throw new NotFoundException(String.format("Sheet(%s) is not found in Excel Workbook(%s)",sheetName,path));
}
else
{
sheet=workbook.getSheetAt(index);
}
}
return sheet;
}
/**
* Depending upon index it returns the sheet object
* @param index - is index of sheet
* @return if sheet exist returns XSSFSheet object else returns null.
*/
public Sheet getSheetAt(int index)
{
if(index<0)
{
throw new NotFoundException(String.format("Sheet is not found @ index = %s", index));
}
else
{
sheet=workbook.getSheetAt(index);
}
return sheet;
}
/**
* This function returns cell contents as string
* @param sheetName name of the sheet
* @param columnNumber
* @param rowNumber
* @return returns cell contents as string
*/
public String getCellData(String sheetName,int rowNumber,int columnNumber)
{
String celldata="";
if(columnNumber>=0 || rowNumber >=0)
{
try
{
sheet=getSheet(sheetName);
Row row=sheet.getRow(rowNumber);
Cell cell= row.getCell(columnNumber);
celldata = getCellContentAsString(cell);
}
catch(NullPointerException e)
{
TALogger.logError("Geting NullPointerException while reading cell => Sheet_Name="+sheetName+" column="+columnNumber+" rownumber="+rowNumber);
return "";
}
catch(Exception ex)
{
TALogger.logError("Geting exception while reading cell => Sheet_Name="+sheetName+" column="+columnNumber+" rownumber="+rowNumber,ex);
return "";
}
}
else
{
throw new TARuntimeException("Invalid index..!! rowIndex= " + rowNumber +" columnIndex="+columnNumber);
}
return celldata;
}
/**
* This function returns cell contents as string
* @param sheetName
* @param columnName
* @param rowNumber
* @return returns cell contents as string
*/
public String getCellData(String sheetName,int rowNumber,String columnName)
{
String celldata="";
sheet=getSheet(sheetName);
int columnNumber=getColumnNumber(0, columnName);
if(columnNumber>=0 || rowNumber >=0)
{
try
{
Row row=sheet.getRow(rowNumber);
Cell cell= row.getCell(columnNumber);
celldata = getCellContentAsString(cell);
}
catch(NullPointerException e)
{
TALogger.logError("Geting NullPointerException while reading cell => Sheet_Name="+sheetName+" column="+columnNumber+" rownumber="+rowNumber);
return "";
}
catch(Exception ex)
{
//This Log Error Should be here. Sometimes we get exception while reading the cell data if the cell is blank.
TALogger.logError("Geting exception while reading cell => Sheet_Name="+sheetName+" column="+columnNumber+" rownumber="+rowNumber,ex);
return "";
}
}
else
{
throw new TARuntimeException("Invalid index..!! rowIndex= " + rowNumber +" columnIndex="+columnNumber);
}
return celldata;
}
public boolean setCellData(String sheetName,int rowNum,String colName,int headerColumnNumber, String data)
{
int columnNumber=getColumnNumber(headerColumnNumber, colName);
boolean result= setCellData(sheetName, rowNum, columnNumber, headerColumnNumber, data);
return result;
}
public boolean setCellData(String sheetName,int rowNum,int columnNum,int headerColumnNumber, String data)
{
try
{
sheet=getSheet(sheetName);
Row row=sheet.getRow(rowNum);
if(row==null)
row=sheet.createRow(rowNum);
sheet.autoSizeColumn(columnNum);
Cell cell=row.getCell(columnNum);
if(cell==null)
cell=row.createCell(columnNum);
cell.setCellValue(data);
writeToExcel(workbook, path);
}
catch(Exception e)
{
throw new TARuntimeException("Problem While setting data @rowNum="+rowNum+ " ColumnNum= "+columnNum,e);
}
return true;
}
/**
*
* @param rowNum
* @param columnName
* @return
*/
public int getColumnNumber(int rowNum, String columnName)
{
int colNum=-1;
if(rowNum>=0 && (!columnName.isEmpty()))
{
Row row=sheet.getRow(rowNum);
for(int i=0;i<row.getLastCellNum();i++)
{
Cell cell = null;
try
{
cell = row.getCell(i);
}
catch(NullPointerException e)
{
TALogger.logError(String.format("Cell number %s is not defined @rowNum = %s", i, rowNum));
}
if( cell != null && cell.getStringCellValue().trim().equalsIgnoreCase(columnName))
{
colNum=i;
break;
}
}
}
if(colNum==-1)
{
TALogger.logDebug("Enable to find column " + columnName + " at row number "+ rowNum);
}
return colNum;
}
/**
* This function returns the total number of column exist in sheet.
* This function consider the first row of the sheet as the column row
* @param sheetName is the name of the sheet
* @return returns the column count
*/
public int getColumnCount(String sheetName)
{
sheet = getSheet(sheetName);
Row row = sheet.getRow(0);
if(row==null)
return -1;
return row.getLastCellNum();
}
/**
* This function returns the total number of columns depending upon columnEndKeyWord.
* E.g It will increase the counter for the columns until it find the columnEndKeyWord in the passed rowNumber.
* MaxColumn count is 200 to avoid the infinite loop
* @param sheetName is the name of the sheet
* @return returns the column count
*/
public int getColumnCount(String sheetName,int rowNumber,String columnEndKeyWord)
{
int MaxColumnCount=200;
int columnCount=0;
int currentColumn=1;
while(currentColumn<=MaxColumnCount)
{
if(getCellData(sheetName,rowNumber,currentColumn).equalsIgnoreCase(columnEndKeyWord))
{
break;
}
else
{
columnCount=columnCount+1;
currentColumn=currentColumn+1;
}
}
return columnCount;
}
/**
*
* @param sheetName
* @return
*/
public int getRowCount(String sheetName)
{
sheet = getSheet(sheetName);
int number=sheet.getLastRowNum();
return number+1;
}
/**
*
* @param cell
* @return
*/
private String getCellContentAsString(Cell cell) throws Exception
{
String celldata="";
switch (cell.getCellType())
{
case Cell.CELL_TYPE_BLANK:
celldata="";
break;
case Cell.CELL_TYPE_STRING:
celldata=cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
DataFormatter df=new DataFormatter();
celldata=df.formatCellValue(cell);
break;
case Cell.CELL_TYPE_FORMULA:
celldata=String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
celldata=String.valueOf(cell.getBooleanCellValue());
break;
default:
celldata=cell.getStringCellValue();
break;
}
return celldata;
}
public synchronized static void writeToExcel(Workbook workbook,String filePath)
{
FileOutputStream fileOut;
try
{
fileOut = new FileOutputStream(filePath);
workbook.write(fileOut);
fileOut.close();
}
catch (IOException e)
{
throw new TARuntimeException(String.format("Problem while writting into the file(%s)",filePath),e);
}
}
}
package readdata;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
public class ReadURL {
public static WebDriver driver;
private static final String FILE_NAME = "Enter Excel path here;
@SuppressWarnings("unused")
private static final boolean String = false;
public static void main(String[] args) throws InterruptedException {
File file = new File(".\\driver\\geckodriver.exe");
System.setProperty("webdriver.gecko.driver", file.getAbsolutePath());
driver = new FirefoxDriver();
String URL = "URL HERE";
driver.get(URL);
System.out.println("URL ENTERED");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
@SuppressWarnings("resource")
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
// convert current cell into string because cell value can't enter into text box
String value = currentCell.getStringCellValue();
// System.out.println(value);
driver.findElement(By.id("enter_website_field")).sendKeys(value);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("starttest_butoon")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
try {
// This is special code to read pseudo element alert
String script = "return window.getComputedStyle(document.querySelector('.analyzer_search_inner.tooltipstered'),':after').getPropertyValue('content')";
Thread.sleep(3000);
JavascriptExecutor js = (JavascriptExecutor) driver;
String content = (String) js.executeScript(script);
System.out.println(content);
if (content.contains("\"Enter url to analyze\"")) {
System.out.println("\nInvalid URL\n" + value);
}
} catch (JavascriptException e) {
System.out.println("\nValid URL\n" + value);
}
driver.findElement(By.id("enter_website_field")).clear();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}