Skip to main content

3 way's to Read from excel......Apache POI- Selenium-MacOS


To work with excel  first we need to have below jars present on the system from Apache POI.

Download files from Binary distribution .tar.gz for Mac and zip from windows, link

once all jar files are downloaded


Go to Java project-> right click-> Build Path-> configure Build path


Add external Jars 


and click apply and OK

If you are using Maven add the Apache POI dependency in POM.XML

Go to Maven repository and search for Apache POI, first 2 dependency will be good to go with


Add the dependency in your POM.XML file

<dependency>

    <groupId>org.apache.poi</groupId>

    <artifactId>poi</artifactId>

    <version>5.0.0</version>

</dependency>

<dependency>

    <groupId>org.apache.poi</groupId>

    <artifactId>poi-ooxml</artifactId>

    <version>5.0.0</version>

</dependency>


And your are good to go with Excel read and write
Eg:-excel present in your system contains the data.



public class Exceldataread {

@Test

public void test1() throws IOException

//"/Users/priyankac/Desktop/testdata.xlsx" is the path of the file which can be taken in Mac system by clicking on file-> Get Info-> copy the the path mentioned under "where" and paste it here, below is the screenshot for reference




 //In windows while giving a path of the excel you need to convert forward slash into double backward slash

//In MAC you don't need to change anything

FileInputStream fis = new FileInputStream("/Users/priyankac/Desktop/testdata.xlsx");

XSSFWorkbook workbook = new XSSFWorkbook(fis);

 //To fetch sheet with Index number

        XSSFSheet sheet = workbook.getSheetAt(0);

 //To fetch sheet with sheet name

             XSSFSheet sheet = workbook.getSheet(Sheet1);

 //To fetch sheet name

System.out.println("sheet name is "+sheet.getSheetName());

//To fetch number of rows

int rows=sheet.getLastRowNum();

System.out.println(rows);

//To fetch number of coulmn

       int cols= sheet.getRow(0).getLastCellNum();

System.out.println(cols);

//This is simple way To fetch all rows and columns present in the sheet including header

//Fetching the first row data

// Header Name O row and O column

System.out.println(sheet.getRow(0).getCell(0).getStringCellValue());

//Header place at 0 row 1st column

System.out.println(sheet.getRow(0).getCell(1).getStringCellValue());

//Header EmpID at 0 row 2nd column

System.out.println(sheet.getRow(0).getCell(2).getStringCellValue());

//Header Rating at 0 row 3rd column

        System.out.println(sheet.getRow(0).getCell(3).getStringCellValue());

//Similarly we can fetch 2nd row data one by one

//Fetching data from 1st row and 0 column

System.out.println(sheet.getRow(1).getCell(0).getStringCellValue());

//Fetching data from 1st row and 1st column

System.out.println(sheet.getRow(1).getCell(1).getStringCellValue());

//Fetching data from 1st row and 2nd column

System.out.println(sheet.getRow(1).getCell(2).getRawValue());

//Fetching data from 1st row and 3rd column

System.out.println(sheet.getRow(1).getCell(3).getRawValue());

}}

//Similarly you can do it for the rest of rows.


Result

If you want Result to be in in a line remove "ln" from print

Result


 To Read all data in the sheet using "for loop"

public class Exceldataread {

@Test

public void test1() throws IOException

FileInputStream fis = new FileInputStream("/Users/priyankac/Desktop/testdata.xlsx");

XSSFWorkbook workbook = new XSSFWorkbook(fis);

        XSSFSheet sheet = workbook.getSheetAt(0);

int rows=sheet.getLastRowNum();

  System.out.println(rows);

int cols= sheet.getRow(0).getLastCellNum();

        System.out.println(cols);

//Traversing through rows

        for (int r=0;r<rows;r++)

        {

XSSFRow row=sheet.getRow(r);

//Traversing through columns

for(int c=0;c<cols;c++)

  {

XSSFCell cell=row.getCell(c);

//Switch is used to returns type of cell (string/numeric/boolean) 

switch(cell.getCellType())

{

//Print command os used to stop same rows going in next line

case STRING: System.out.print(cell.getStringCellValue()); break;

case NUMERIC: System.out.print(cell.getNumericCellValue());break;

case BOOLEAN: System.out.print(cell.getBooleanCellValue());break;

}

// Pipe is used to create distance between 2 fields within a row

System.out.print(" | ");

}

//one row to another data should be written in next line

System.out.println(); 

       }

}

}


Result

Reading the excel using Iterator method

public class Exceldataread {

@Test

public void test1() throws IOException

FileInputStream fis = new FileInputStream("/Users/priyankac/Desktop/testdata.xlsx");

XSSFWorkbook workbook = new XSSFWorkbook(fis);

        XSSFSheet sheet = workbook.getSheetAt(0);

//Iterator object is created for sheet

        Iterator it = sheet.iterator();
//Capture the next value in a row

           while(it.hasNext())

                {

//XSSF row typecasting should be used

           XSSFRow row =(XSSFRow) it.next();

//Iterator  should be applied on cell level

Iterator cellIt =row.cellIterator();

//To read all cells while loop is used

    while(cellIt.hasNext())

                 {

           XSSFCell cell=(XSSFCell) cellIt.next();

//Switch is used to returns type of cell (string/numeric/boolean) 

switch(cell.getCellType())

{

case STRING: System.out.print(cell.getStringCellValue()); break;

case NUMERIC: System.out.print(cell.getNumericCellValue());break;

case BOOLEAN: System.out.print(cell.getBooleanCellValue());break;

}

// Pipe is used to create distance between 2 fields within a row

System.out.print(" | ");

}

//one row to another data should be written in next line

System.out.println();

}

}}


Result

Check the final run video here

Comments

Popular posts from this blog

Cucumber - Execution of test cases and reporting

Before going through this blog please checkout blog on   Cucumber Fundamentals Cucumber is testing tool which implements BDD(behaviour driven development).It offers a way to write tests that  anybody can understand, regardless of there technical knowledge. It users Gherkin (business readable language) which helps to  describe behaviour without going into details of implementation It's helpful for  business stakeholders who can't easily read code ( Why cucumber tool,  is  called  cucumber , I have no idea if you ask me I could have named it "Potato"(goes well with everything and easy to understand 😂) Well, According to its founder..... My wife suggested I call it  Cucumber  (for no particular reason), so that's how it got its  name . I also decided to give the Given-When-Then syntax a  name , to separate it from the  tool . That's why it's  called  Gherkin ( small variety of a cucumber that's been pickled. I...

Jmeter 5.4.1- Config Elements - Part-03

  Part-01- Installation of Jmeter and HTTP's Recorder click  here Part 02--Previous blog on Assertion Config elements in Jmeter are used to configure or modify the samplers requests made to the server. These elements are added at the same or higher level of the samplers that we want to configure  Let' start with  CSV data config As the name suggest it used to read data from CSV first we need to put data in variables and then use the variables in sampler request. create a new test plan add CSV data set config Add a Thread Group and then add Sampler "Java Request"  Create a CSV file  with some data (Name and Data) and save it  Now go to Jmeter CSs data set config browse and upload the css file create Make few more changes in place of  variable name - Name and Dept Ignore first line - True Delimeter - \t (as suggested) Now move on the Sampler-" Java Request" and rename it with header elements of CSV As we have Name and d...

Beginners tutorial -:working with JMeter in Mac and windows - Part-01

  Prequisite   you should have Java downloaded in your system with Home path set under environment variables.(as of today Java version 8 and higher are required fro jmeter ) for help check out this link Note Always run the jmeter on your secondary browser,  if you give the primary browser for proxy settings then your internet connection will be disrupted for the browser as well as system For ex if you have chrome and firefox and your primary or default browser is chrome then do all the proxy setting in firefox so it won't hamper the system Internet connection  if you have safari as your default browser in your mac os then set proxy in chrome/firefox  MAC Download jmeter from the link  here click on the hypelink under section Binaries  "Apache JMeter( 5.3 ). tgz" file  for Mac   Tar file will get downloaded Double click on the tar file to unzip  once you open the folder  got to bin and search for jmeter.sh file this is a executa...