I'm new to Selenium WebDriver and still learning. I just want to read the data from the excel and write the data either in a same excel sheet or different excel sheet.
User name and passwor for login is stored in excel sheet in two columns. I want to read the username/password from the excel sheet. If it's a valid user name/pwd I just wanted to Write "Pass" in new column else I need to write it as "Fail"
My code works successfully for reading data from excel sheet. However i'm stuck with writing data in excel sheet.
Thanks for reading and coming forward to clear my doubt.
Consider using Apache POI for reading and writing the excel. May be you can write a simple Util class which reads and writes excel .
To get the user id and password the util class should have a method to read excel and pass it to your selenium script.
Once the credentials are validated util class should have a method to write pass/fail to your excel.
Sample code to create row and write to a cell using POI
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");
Refer this Example
In your case you may just need to iterate the existing excel then read/write.
The following Selenium Java code using Apache POI should work:
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)
{
}
}
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);
}
}
}
# Read data from excel in #selenium
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();
}
}
}
Related
I have trouble reading the information in an Excel file to introduce and test with selenium. But the result always NullPoInterException. I tried to change the link in the Excel file. Here’s the 2-part code.
public class TestProviderII {
public static void main(String[] args) {
String url = ".\\src\\test\\resources\\dataProvider.xlsx";
testData(url, "SheetOne");
}
public static void testData(String url, String sheet) {
ExcelUtils excelUtils = new ExcelUtils(url, sheet);
int rowCount = excelUtils.getRowCount();
int colCount = excelUtils.getColCount();
for (int i = 1; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
String cellData = excelUtils.getCellDataString(i, j);
System.out.println("Data : " + cellData);
}
}
}
}
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
static XSSFWorkbook workbook;
static XSSFSheet sheet;
public ExcelUtils(String workBook, String sheetName) {
try {
workbook = new XSSFWorkbook(workBook);
sheet = workbook.getSheet(sheetName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getRowCount() {
int rowCount = 0;
try {
rowCount = sheet.getPhysicalNumberOfRows();
System.out.println("No of Row : " + rowCount);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return rowCount;
}
public static int getColCount() {
int colCount = 0;
try {
colCount = sheet.getRow(0).getPhysicalNumberOfCells();
System.out.println("No of Column" + colCount);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return colCount;
}
public static String getCellDataString(int rowNum, int colNum) {
String cellData = "";
try {
cellData = sheet.getRow(rowNum).getCell(colNum).getStringCellValue();
System.out.println("Data Cell : " + cellData);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return cellData;
}
public static Double getCellDataNumber(int rowNum, int colNum) {
double cellData = 0;
try {
cellData = sheet.getRow(rowNum).getCell(colNum).getNumericCellValue();
System.out.println(cellData);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return cellData;
}
}
And the result is NullPointerException
null
null
null
null
java.lang.NullPointerException
at test.ExcelUtils.getRowCount(ExcelUtils.java:23)
at test.TestProviderII.testData(TestProviderII.java:12)
at test.TestProviderII.main(TestProviderII.java:7)
java.lang.NullPointerException
at test.ExcelUtils.getColCount(ExcelUtils.java:36)
at test.TestProviderII.testData(TestProviderII.java:13)
at test.TestProviderII.main(TestProviderII.java:7)
Process finished with exit code 0
Why the result nullPointerException despite I did exactly what said?
And I changed the Excel file link and the result is the same.
String url = ".\\src\\test\\resources\\dataProvider.xlsx";
String url = "src\\test\\resources\\dataProvider.xlsx";
String url = "C:\\Selenuim\\demoApplication\\src\\test\\resources\\dataProvider.xlsx
Change below line:
testData(url, "SheetOne");
to:
testData(url, "Sheet1");
Assuming the sheet looks like below in your excel file:
Also ensure, there is some data in your excel sheet. I ran your code by just changing to Sheet1. And it worked see below:
Excel sheet:
Console Output:
No of Column3
Data Cell : d
Data : d
Data Cell : e
Data : e
Data Cell : f
Data : f
I have code for witting data in Excel file whenever cell founds empty. However when i type below code it gives error. :
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
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.apache.poi.ss.usermodel.Row;
import Config.Constants;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row, xRow;
public static void setExcelFile(String Path, String SheetName) throws Exception {
// TODO Auto-generated method stub
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
// ExcelWSheet = ExcelWBook.getSheet(SheetName);
}
public static String getCellData(int RowNum, int ColNum, String SheetName) throws Exception {
ExcelWSheet = ExcelWBook.getSheet(SheetName);
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
public static int getRowCount(String SheetName) {
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int number = ExcelWSheet.getLastRowNum() + 1;
return number;
}
//This method is to get the Row number of the test case
//This methods takes three arguments(Test Case name , Column Number & Sheet name)
public static int getRowContains(String sTestCaseName, int colNum, String SheetName) throws Exception {
int i;
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int rowCount = ExcelUtils.getRowCount(SheetName);
for (i = 0; i < rowCount; i++) {
if (ExcelUtils.getCellData(i, colNum, SheetName).equalsIgnoreCase(sTestCaseName)) {
break;
}
}
return i;
}
//This method is to get the count of the test steps of test case
//This method takes three arguments (Sheet name, Test Case Id & Test case row number)
public static int getTestStepsCount(String SheetName, String sTestCaseID, int iTestCaseStart) throws Exception {
for (int i = iTestCaseStart; i <= ExcelUtils.getRowCount(SheetName); i++) {
if (!sTestCaseID.equals(ExcelUtils.getCellData(i, Constants.Col_TestCaseID, SheetName))) {
int number = i;
return number;
}
}
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int number = ExcelWSheet.getLastRowNum() + 1;
return number;
}
#SuppressWarnings("static-access")
public static void setCellData(String Result, int RowNum, int ColNum, String SheetName) throws Exception {
try {
ExcelWSheet = ExcelWBook.getSheet(SheetName);
Row = ExcelWSheet.getRow(RowNum);
xRow = ExcelWSheet.getRow(RowNum);
// Row.RETURN_BLANK_AS_NULL;
// ExcelWBook.setMissingCellPolicy(Row.RETURN_BLANK_AS_NULL);
//Cell = Row.getCell(ColNum, Blank);
Cell = xRow.getCell(ColNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (Cell == null) {
Cell = Row.createCell(ColNum);
Cell.setCellValue(Result);
} else {
Cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new FileOutputStream(Constants.Path_TestData);
//ExcelWBook.write(fileOut);
ExcelWBook.write(fileOut);
//fileOut.flush();
fileOut.close();
ExcelWBook = new XSSFWorkbook(new FileInputStream(Constants.Path_TestData));
} catch (Exception e) {
DriverScript.bResult = false;
}
}
}
Error message:
MissingCellPolicy cannot be resolved or is not a field
Whereas when i use "Row.RETURN_BLANK_AS_NULL" it says method is deprecated. Can i have some solution for this both problems to run my code succesfully?
Cell has many types and you should get value according to its type, getStringCellValue() is not enough
I often use this code to get
switch (cell.getCellTypeEnum()) {
case FORMULA:
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellTypeEnum()) {
case BOOLEAN:
value = Boolean.toString(cellValue.getBooleanValue());
break;
case NUMERIC:
value = Double.toString(cellValue.getNumberValue());
break;
case STRING:
value = cellValue.getStringValue();
break;
}
break;
case BOOLEAN:
value = Boolean.toString(cell.getBooleanCellValue());
break;
case NUMERIC:
value = Double.toString(cell.getNumericCellValue());
break;
default:
value = cell.getStringCellValue();
break;
}
I want to return the values present in an excel file but it is returning values like [[Ljava.lang.String;#490ab905. Data is not returning the values like user name. Used jxl and data provider. Even i am not aware of data provider much. Please help me to fetch the accurate values from excel.
Following are my code:
public class excelUtil {
// public String suiteFileName = "/suite.xls";
String testDatafile = "/src/testData/testdata.xls";
// public String testDatafile = "/testdata/Testdata.xls";
#DataProvider
public Object[][] getTestData(String sheetName)
{
//String getTestData(String sheetName, int rowNumber, int colNum) {
// Read Excel
String path = System.getProperty("user.dir") + testDatafile;
Workbook w = null;
File inputWorkbook = new File(path);
// Open workbook
try {
w = Workbook.getWorkbook(inputWorkbook);
} catch (BiffException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the first sheet
Sheet sheet = w.getSheet(sheetName);
//Loop over first 10 column and lines
// Get the first sheet
//Loop over first 10 column and lines
int rowCount = sheet.getRows();
int columnCount = sheet.getColumns();
Object[][] data = new String[rowCount-1][columnCount];
for(int i=1;i<rowCount;i++)
{
Cell cell = sheet.getCell(0, i);
String value = cell.getContents().toString();
System.out.println(value);
data[i-1][0]= value.toString();
System.out.println(data[i-1][0]);
cell = sheet.getCell(1, i);
value = cell.getContents().toString();
data[i-1][1]= value.toString();
}
w.close();
//System.out.println(value);
System.out.println(data);
return data;
}
public static WebDriver driver ;
#Test(dataProvider = "getTestData")
public void OrpakLoginTest(Object username, Object password) {
driver = new FirefoxDriver();
driver.get("http:orpakqa.commdel.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Loginelements lg = new Loginelements();
WebElement element_UserName = lg.getOrpakUserNameField(driver);
element_UserName.sendKeys(username.toString());
WebElement element_Password = lg.getOrpakPasswordField(driver);
element_Password.sendKeys(password.toString());
//WebElement element_LoginBtn = lg.getOrpakLoginButton(driver);
//element_LoginBtn.click();
}
Use POI Jars
https://poi.apache.org/download.html
Below code is working for me:-
public String getXLcellValue(String xlpath, String sheetName, int rowNum, int cellNum)
{
try{
FileInputStream fis=new FileInputStream(xlpath);
Workbook wb=WorkbookFactory.create(fis);
Log.info("Get the value from the cell(getXLcellValue)");
return wb.getSheet(sheetName).getRow(rowNum).getCell(cellNum).getStringCellValue();
}
catch(Exception ex)
{
Log.info("Error in getXLcellValue ="+ ex.getMessage());
}
return "";
}
xlpath = path of excel file in your system
Sheetname = name of the sheet in excel file
row = row number of username or password
cellnum = cell number of username or password
You can update your code as below and I hope this solution work for you:
import java.io.File;
import jxl.Sheet;
import jxl.Workbook;
import org.openqa.selenium.By;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ProApp extends OneClass {
Workbook wb;
Sheet sh1;
int numrow;
String username;
String password;
#BeforeMethod
public void oneTimeSetUp() throws InterruptedException {
driver.manage().window().maximize();
driver.get("Testing.com");
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id='app']/div/main/section/ul/li[1]/a")).click();
Thread.sleep(1000);
}
#Test(dataProvider="testdata")
public void testFireFox(String uname,String password1) throws InterruptedException
{
driver.findElement(By.xpath("//input[#name='username']")).clear();
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='username']")).sendKeys(uname);
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='password']")).clear();
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='password']")).sendKeys(password1);
Thread.sleep(1000);
driver.findElement(By.xpath("//button[#name='loginButton']")).click();
Thread.sleep(1000);
}
#DataProvider(name="testdata")
public Object[][] TestDataFeed(){
try {
// load workbook
wb=Workbook.getWorkbook(new File("C://File//Book2.xls"));
// load sheet in my case I am referring to first sheet only
sh1= wb.getSheet(0);
// get number of rows so that we can run loop based on this
numrow= sh1.getRows();
}
catch (Exception e)
{
e.printStackTrace();
}
// Create 2 D array and pass row and columns
Object [][] logindata=new Object[numrow][sh1.getColumns()];
// This will run a loop and each iteration it will fetch new row
for(int i=0;i<numrow;i++){
// Fetch first row username
logindata[i][0]=sh1.getCell(0,i).getContents();
// Fetch first row password
logindata[i][1]=sh1.getCell(1,i).getContents();
}
// Return 2d array object so that test script can use the same
return logindata;
}
}
this is what i have tried
public class UniqueUSER
{
static HSSFWorkbook hwb=new HSSFWorkbook();
static HSSFSheet sheet = hwb.createSheet("new sheet");
public static void main(String[]args) throws IOException
{
HSSFRow row;
HashSet<String> names = new HashSet<>();
BufferedReader br = new BufferedReader (new FileReader("Sample.log"));
PrintStream out=new PrintStream("D:/Excel.xls");
String str=null;
while((str=br.readLine())!=null)
{
if(str.contains("FLTR"))
{
String user=str.substring(97, 135);
names.add(user);
HSSFRow row1 = sheet.createRow((short)count);
}
}
Iterator itr=names.iterator();
while(itr.hasNext())
{
out.println(itr.next());
}
}
}
This program storing values to excel sheet but when i read same file using following program, I am getting exception and errors..
public class Country1
{
private String name;
private String shortCode;
public Country1(String n, String c)
{
this.name=n;
this.shortCode=c;
}
public void Country(String name2, String shortCode2)
{
// TODO Auto-generated constructor stub
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getShortCode()
{
return shortCode;
}
public void setShortCode(String shortCode)
{
this.shortCode = shortCode;
}
#Override
public String toString()
{
return name + "::" + shortCode;
}
}
public class ReadExcel
{
public static List<Country1> readExcelData(String fileName)
{
List<Country1> countriesList = new ArrayList<Country1>();
try
{
//Create the input stream from the xlsx/xls file
FileInputStream fis = new FileInputStream(fileName);
//Create Workbook instance for xlsx/xls file input stream
Workbook workbook = null;
if(fileName.toLowerCase().endsWith("xlsx"))
{
workbook = new XSSFWorkbook(fis);
}
else if(fileName.toLowerCase().endsWith("xls"))
{
workbook = new HSSFWorkbook(fis);
}
//Get the number of sheets in the xlsx file
int numberOfSheets = workbook.getNumberOfSheets();
//loop through each of the sheets
for(int i=0; i < numberOfSheets; i++)
{
//Get the nth sheet from the workbook
Sheet sheet = workbook.getSheetAt(i);
//every sheet has rows, iterate over them
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
String name = "";
String shortCode = "";
//Get the row object
Row row = rowIterator.next();
//Every row has columns, get the column iterator and iterate over them
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
//Get the Cell object
Cell cell = cellIterator.next();
//check the cell type and process accordingly
switch(cell.getCellType())
{
case Cell.CELL_TYPE_STRING:
if(shortCode.equalsIgnoreCase(""))
{
shortCode = cell.getStringCellValue().trim();
}
else if(name.equalsIgnoreCase(""))
{
//2nd column
name = cell.getStringCellValue().trim();
}
else
{
//random data, leave it
System.out.println("Randomdata::"+cell.getStringCellValue());
}
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Random data::"+cell.getNumericCellValue());
}
} //end of cell iterator
Country1 c = new Country1(name, shortCode);
countriesList.add(c);
} //end of rows iterator
} //end of sheets for loop
//close file input stream
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return countriesList;
}
public static void main(String args[])
{
List<Country1> list = readExcelData("D:\\Excel.xls");
System.out.println("Country List\n"+list);
}
}
I am confused which program is correct and which one is wrong.. please someone could help me.. thanks lot
Exception are like below:
Unable to read entire header; 320 bytes read; expected 512 bytes
at org.apache.poi.poifs.storage.HeaderBlock.alertShortRead(HeaderBlock.java:227)
at org.apache.poi.poifs.storage.HeaderBlock.readFirst512(HeaderBlock.java:208)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:128)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:342)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:323)
at com.unisys.ReadExcel.readExcelData(ReadExcel.java:32)
at com.unisys.ReadExcel.main(ReadExcel.java:97)
Country List
[]
try to change
Iterator<Row> rowIterator = sheet.iterator();
to
Iterator<Row> rowIterator = sheet.rowIterator()
Also, when writing your create rows, but you do not write anything to them
HSSFRow row1 = sheet.createRow((short)count);
then create cell
row.createCell (0).setCellValue (user);
Update
Just had another look at your code, why on earth are you doing
PrintStream out=new PrintStream("D:/Excel.xls");
Use the POI API to create the xls.
Actually i am working on a java program that extracts data from an Excel file,
and i am using the POI Library, as a matter of fact i must specify the type of every extracted value, but the file contains a huge number of data with different types,
So i am asking if there is another way to get all the data as a string.
Thank you.
Best regards
package DAO;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Vector;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class ReadExcelFile {
public static void main(String[] args) {
String fileName = "C:\\Users\\marrah\\Desktop\\TRIAL FILE1.xls";
Vector dataHolder = ReadCSV(fileName);
printCellData(dataHolder);
}
public static Vector ReadCSV(String fileName) {
Vector cellVectorHolder = new Vector();
try {
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector = new Vector();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreVector.addElement(myCell);
}
cellVectorHolder.addElement(cellStoreVector);
}
} catch (Exception e) {
e.printStackTrace();
}
return cellVectorHolder;
}
private static void printCellData(Vector dataHolder) {
for (int i = 0; i < dataHolder.size(); i++) {
Vector cellStoreVector = (Vector) dataHolder.elementAt(i);
for (int j = 0; j < cellStoreVector.size(); j++) {
HSSFCell myCell = (HSSFCell) cellStoreVector.elementAt(j);
Object stringCellValue="";
stringCellValue =cellStoreVector.get(j).toString();
System.out.print(stringCellValue.toString()+"\t");
}
}
}
}
I have a unit-test where I use the following to extract all text from an Excel file without any of the formatting, for some use-cases this might be quicker than iterating over all the elements one-by-one:
private POITextExtractor extractText(File file) throws IOException {
InputStream inp = null;
try {
inp = new PushbackInputStream(
new FileInputStream(file), 8);
if(POIFSFileSystem.hasPOIFSHeader(inp)) {
return createExtractor(new POIFSFileSystem(inp));
}
throw new IllegalArgumentException("Your File was neither an OLE2 file, nor an OOXML file");
} finally {
if(inp != null) inp.close();
}
}
private static POITextExtractor createExtractor(POIFSFileSystem fs) throws IOException {
return createExtractor(fs.getRoot(), fs);
}
private static POITextExtractor createExtractor(DirectoryNode poifsDir, POIFSFileSystem fs) throws IOException {
for(Iterator<Entry> entries = poifsDir.getEntries(); entries.hasNext(); ) {
Entry entry = entries.next();
if(entry.getName().equals("Workbook")) {
{
return new ExcelExtractor(poifsDir, fs);
}
}
}
throw new IllegalArgumentException("No supported documents found in the OLE2 stream");
}
private String assertContains(File file, String... contents) throws IOException {
assertTrue(file.exists());
POITextExtractor extractor = extractText(file);
assertNotNull(extractor);
String str = extractor.getText();
for(String s : contents) {
assertTrue("Did expect to find text '" + s + "' in resulting Excel file, but did not find it in str: " + str, str.contains(s));
}
return str;
}
You can create a common function to use on every cell when you runs thru each row, which validates the data type and then retrieves it in your preferred format. So you move row to row and, for each cell you call something like:
private static String getCellvalue(HSSFRow poiRow, int intColActual) {
if (poiFilaActual != null && poiRowActual.getLastCellNum() >= (short) intColActual) {
HSSFCell cell = poiRowActual.getCell(intColActual);
if (cell != null) {
if (HSSFCell.CELL_TYPE_STRING == cell.getCellType()) {
return cell.getRichStringCellValue().toString();
} else if (HSSFCell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
return new String( (cell.getBooleanCellValue() == true ? "true" : "false") );
} else if (HSSFCell.CELL_TYPE_BLANK == cell.getCellType()) {
return "";
} else if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
if(HSSFDateUtil.isCellDateFormatted(cell)){
return ( new SimpleDateFormat("dd/MM/yyyy").format(cell.getDateCellValue()) );
}else{
return new BigDecimal(cell.getNumericCellValue()).toString();
}
}
}
}
return null;
}