how to get data from excel file? - java

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;
}

Related

How to set the excel file's visibility to true

I am creating a new excel file using Apache POI and I would like to set the file's visibility to true. What function or code do I use to show the file after I create it using Apache POI rather than just saving it in a directory?
I have tried the following line of code which is similar to what we use in LotusScript but I got a "Instance member VISIBLE does not exist" error on that line.
ExcelApplication.Visible = True
Below is the code I'm using to write the excel file, which does work correctly as it saves the file in the directory I specified in the 'fileName'.
public boolean writeExcelFile(String fileName) {
try {
//Auto fit content
for(int i = 0; i < 20; i++) {
this.wbSheet.autoSizeColumn((short)i);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(fileName);
this.wb.write(fileOut);
fileOut.close();
} catch(Exception ex) {
ex.printStackTrace();
return(false);
}
return(true);
}
I expect the excel file to be created and opened rather than saved on the computer.
The VBA code line ExcelApplication.Visible = True, where ExcelApplication would must be an Application object, can only work because VBA works directly together with the Microsoft Office applications. This is not what apache poi is doing. Apache poi's goal is creating files in the Microsoft Office file formats. Neither it needs any installed Microsoft Office application nor it tries to interact with those applications.
So after apache poi is ready with it's work, then you always will get a file in the appropriate Microsoft Office file format. The only thng you could do then is opening that file using java.awt.Desktop. For example:
public boolean openExcelFile(String fileName) {
try {
File file = new File(fileName);
Desktop.getDesktop().open(file);
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
Complete Example:
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.GregorianCalendar;
import java.awt.Desktop;
class CreateExcelAndOpenFile {
private Workbook workbook;
private Sheet sheet;
public CreateExcelAndOpenFile() {
this.workbook = new XSSFWorkbook();
this.sheet = this.workbook.createSheet();
}
public Workbook getWorkbook() {
return this.workbook;
}
public boolean writeDataInSheet(Object[][] data, String[] columnCellTypes, CellStyle[] columnCellStyles) {
try {
FormulaEvaluator formulaEvaluator = this.workbook.getCreationHelper().createFormulaEvaluator();
for (int r = 0; r < data.length; r++) {
Row row = this.sheet.createRow(r);
for (int c = 0; c < data[0].length; c++) {
Cell cell = row.createCell(c);
if (r == 0) {
cell.setCellValue((String)data[r][c]); // header row, all String
cell.setCellStyle(columnCellStyles[c]);
} else if ("number".equals(columnCellTypes[c]) && data[r][c] instanceof Double) {
cell.setCellValue((Double)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
} else if ("date".equals(columnCellTypes[c]) && data[r][c] instanceof GregorianCalendar) {
cell.setCellValue((GregorianCalendar)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
} else if ("text".equals(columnCellTypes[c]) && data[r][c] instanceof String) {
cell.setCellValue((String)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
} else if ("formula".equals(columnCellTypes[c]) && data[r][c] instanceof String) {
cell.setCellFormula((String)data[r][c]);
cell.setCellStyle(columnCellStyles[c]);
formulaEvaluator.evaluateFormulaCell(cell);
}
}
}
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean writeExcelFile(String fileName) {
try (FileOutputStream fileOut = new FileOutputStream(fileName) ) {
// auto fit content
int columnsCountInHeaderRow = this.sheet.getRow(0).getLastCellNum();
for(int i = 0; i < columnsCountInHeaderRow; i++) {
this.sheet.autoSizeColumn((short)i);
}
// write the output to a file
this.workbook.write(fileOut);
this.workbook.close();
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean openExcelFile(String fileName) {
try {
File file = new File(fileName);
Desktop.getDesktop().open(file);
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
public static void main(String[] args) throws Exception {
String fileName = "./Excel.xlsx";
CreateExcelAndOpenFile application = new CreateExcelAndOpenFile();
Object[][] data = new Object[][] {
new Object[] {"Name", "Value", "Date", "Formatted value", "Formula"},
new Object[] {"Lorem", 123.456789, new GregorianCalendar(2019, 0, 15), 123.456789, "ROUND(B2,2)"},
new Object[] {"Ipsum", 1234.56789, new GregorianCalendar(2019, 5, 15), 1234.56789, "ROUND(B3,2)"}
};
String[] columnCellTypes = new String[]{"text", "number", "date", "number", "formula"};
DataFormat dataFormat = application.getWorkbook().createDataFormat();
CellStyle dateStyle = application.getWorkbook().createCellStyle();
dateStyle.setDataFormat(dataFormat.getFormat("DDDD, MMMM, DD, YYYY"));
CellStyle numberStyle = application.getWorkbook().createCellStyle();
numberStyle.setDataFormat(dataFormat.getFormat("#,##0.00 \" Coins\""));
CellStyle[] columnCellStyles = new CellStyle[]{null, null, dateStyle, numberStyle, null};
boolean success = application.writeDataInSheet(data, columnCellTypes, columnCellStyles);
System.out.println(success);
if (success) {
success = application.writeExcelFile(fileName);
System.out.println(success);
if (success) {
success = application.openExcelFile(fileName);
System.out.println(success);
if (success) {
System.out.println("Done successfully");
}
}
}
}
}

Why I cant return the value in the method in selenium?

I already create a method that can return the value in the excel but when i run the main scripts that call the method, the value cannot be return. Maybe there is a problems with my code but i do not know which part that i need to fix.
This is the script that call the method.
GetExcel res = new GetExcel();
String maker = res.getExcel("IS Maker Username");
GetExcel res1 = new GetExcel();
String passMaker = res1.getExcel("IS Maker Password");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#name='userName']")));
driver.findElement(By.xpath("//input[#name='userName']")).click();
driver.findElement(By.xpath("//input[#name='userName']")).sendKeys(maker);
driver.findElement(By.xpath("//input[#name='password']")).click();
driver.findElement(By.xpath("//input[#name='password']")).sendKeys(passMaker);
driver.findElement(By.name("submitLogin")).click();
This is the method function
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
#Test
public class GetExcel {
private XSSFWorkbook wb;
public String getExcel(String getName) throws IOException {
File src = new File("C:\\selenium\\ExcelData\\TestData.xlsx");
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
XSSFSheet sh1 = wb.getSheetAt(0);
String getValue = null;
String value = null;
for (int i = 1; i<=1000; i++) {
if(sh1.getRow(i).getCell(0) != null)
{
getValue = sh1.getRow(i).getCell(0).getStringCellValue();
}
if(getValue != null) {
if(getValue.contains(getName)) {
if(sh1.getRow(i).getCell(1) != null)
{
value = sh1.getRow(i).getCell(1).getStringCellValue();
}
System.out.println(value);
fis.close();
break;
}
}
}
return value;
}
}
The method function was imported from different packages
1.Your code will always return null value because you are comparing cell value with excel sheet_Name.
2.While you are returning value your second column it should not be empty.
3.If you are trying to fetch any value that is number,you should put ' before number in cell like '12345
Modified your code Now try.
public String getExcel(String getName) throws IOException {
File src = new File("C:\\selenium\\ExcelData\\TestData.xlsx");
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
XSSFSheet sh1 = wb.getSheet(getName);
String getValue = null;
String value = null;
int number=sh1.getLastRowNum()+1;
System.out.println("Total used rows :" + number);
for (int i = 1; i<number; i++) {
if(sh1.getRow(i).getCell(0) != null)
{
getValue = sh1.getRow(i).getCell(0).getStringCellValue();
}
if(getValue != null) {
if(!getValue.contains(getName)) {
if(sh1.getRow(i).getCell(1) != null)
{
value = sh1.getRow(i).getCell(1).getStringCellValue();
}
System.out.println(value);
fis.close();
break;
}
}
}
return value;
}
Here is the main function call.
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
GetExcel res = new GetExcel();
String maker = res.getExcel("IS Maker Username");
System.out.println("User :" + maker);
GetExcel res1 = new GetExcel();
String passMaker = res1.getExcel("IS Maker Password");
System.out.println("Password :" + passMaker);
}
Please let me know whether it works for you.

Apache POI error message displayed for RETURN_BLANK_AS_NULL

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;
}

Apache POI event API Update existing Excel sheet

I have large excel file with several worksheets.
I want to process just one sheet in file...Read value from two columns and update two columns.
Using this code, I am able to read data from sheet.But unable to figure out, how to save output back.
public class ExcelFunctions {
private class ExcelData implements SheetContentsHandler {
private Record rec ;
public void startRow(int rowNum) {
rec = new Record();
output.put("R"+rowNum, rec);
}
public void endRow(int rowNum) {
}
public void cell(String cellReference, String formattedValue,
XSSFComment comment) {
int thisCol = (new CellReference(cellReference)).getCol();
if(thisCol==7){
try {
rec.setK1(formattedValue);
} catch (Exception e) {
}
}
if(thisCol==8){
try {
rec.setK2(formattedValue);
} catch (Exception e) {
}
}
if(thisCol == 27){
String key = rec.full_key();
System.out.println(key);
///////Process Matched Key...get Data
//////Set value to column 27
}
if(thisCol == 28){
String key = rec.full_key();
System.out.println(key);
///////Process Matched Key...get Data
//////Set value to column 28
}
}
public void headerFooter(String text, boolean isHeader, String tagName) {
}
}
///////////////////////////////////////
private final OPCPackage xlsxPackage;
private final Map<String, Record> output;
public ExcelFunctions(OPCPackage pkg, Map<String, Record> output) {
this.xlsxPackage = pkg;
this.output = output;
}
public void processSheet(
StylesTable styles,
ReadOnlySharedStringsTable strings,
SheetContentsHandler sheetHandler,
InputStream sheetInputStream)
throws IOException, ParserConfigurationException, SAXException {
DataFormatter formatter = new DataFormatter();
InputSource sheetSource = new InputSource(sheetInputStream);
try {
XMLReader sheetParser = SAXHelper.newXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(
styles, null, strings, sheetHandler, formatter, false);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
} catch(ParserConfigurationException e) {
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
}
}
public void process()
throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
boolean found = false;
while (iter.hasNext() && !found) {
InputStream stream = iter.next();
String sheetName = iter.getSheetName();
if(sheetName.equals("All Notes") ){
processSheet(styles, strings, new ExcelData(), stream);
found = true;
}
stream.close();
}
}
#SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
File xlsxFile = new File("C:\\Users\\admin\\Downloads\\Unique Name Macro\\big.xlsm");
if (!xlsxFile.exists()) {
System.err.println("Not found or not a file: " + xlsxFile.getPath());
return;
}
// The package open is instantaneous, as it should be.
OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ_WRITE);
Map<String, Record> output = new HashMap<String, Record>();
ExcelFunctions xlFunctions = new ExcelFunctions(p, output);
xlFunctions.process();
p.close();
if (output != null){
for(Record rec : output.values()){
System.out.println(rec.full_key());
}
}
}
}
File is very large and I only want to use Event API.
I have successfully tested Using this code.
But this loads Whole file in memory(causing application to crash)...While I only need to edit One sheet.
public static void saveToExcel(String ofn, Map<String, Record> data) {
FileInputStream infile;
try {
infile = new FileInputStream(new File("C:\\Users\\admin\\Downloads\\Unique Name Macro\\big.xlsm"));
XSSFWorkbook workbook = new XSSFWorkbook (infile);
XSSFSheet sheet = workbook.getSheet("All Notes");
for(Record rec : output.values()){
Row dataRow = rec.getRow(rev.getRownum-1);
setCellValue(dataRow, 26, "SomeValue");
setCellValue(dataRow, 27, "SomeValue");
}
FileOutputStream out = new FileOutputStream(new File(ofn));
workbook.write(out);
infile.close();
out.close();
workbook.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void setCellValue(Row row,int col, String value){
Cell c0 = row.getCell(col);
if (c0 == null){
c0 = row.createCell(col);
}
c0.setCellValue(value);
}
I don't think there is anything provided in POI out of the box which allows to do that.
Therefore you might be better off doing this by unzipping the XLSX/XLSM file (they are actually a bunch of xml-files inside a zip) and reading the xml-files as text-files or with a normal XML Parser so that you can easily write out the changed file again to produce the XLSX/XLSM file again.

Read and write excel in Selenium WebDriver

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();
}
}
}

Categories

Resources