Selenium Webdriver Appium Complete TutorialSelenium Webdriver Appium Complete Tutorial
Automation Testing
  • Tools
    • Selenium
      • Selenium Java Tutorial
      • Selenium C# Tutorial
    • Appium
      • Appium Java Tutorial
      • Appium C#Tutorial
    • Katalon
  • Trainings
  • TestNG
  • Reports
    • Extent Reports
      • Extent Reports – Java
      • Extent Reports – Java -Version3
      • Extent Reports – C#
    • Vigo Reports
    • AT Excel Report
  • Excel
    • Apache POI – Java
    • Excel With C#
  • Interview Questions
    • Selenium Interview Questions
    • Java Interview Questions
    • C# Interview Questions
  • Demo Site
  • Practice Site
  • More…
    • AutoIt
    • Sikuli
    • Robot Class
    • File Upload
    • ScreenShot
      • AShot
      • ShutterBug
  • About
December 28, 2016

Read Data From Excel Using Column Name





Read data from excel using column name will discuss about how we can read test data from the excel sheet while automating any application using selenium webdriver. We might get doubt that why we need to put the test data in excel and why to read data from that. If an application need so much of data to be feeded to test; then we will manage those data using external sources like text file, xml file and excel file etc… . Among these; Excel is very user friendly that we can organize the data very easily and we can read the data how we want. So, we mostly use excel to maintain the test data. In order to create a data driven framework then it is easy with using excel.

So, if you want to read data from excel; we need to use some third party API which are available. In those one of the famous is Apache POI. In this blog we will use Apache POI to read the data from the excel sheet. To interact with the excel, Apache POI given so many classes to interact with the excel and get the data. To read excel data we will use Java and Apache POI classes.

Below are the classes will use to read the data:

  1. FileInputStream – A FileInputStream is an inputstream for reading data from a File.
  2. XSSFWorkbook
  3. XSSFSheet
  4. XSSFRow
  5. XSSFCell





Below are the methods will use to read the data which are available in the above classes:

  1. getSheet(“sheetName”) – Get sheet with the given name
  2. getLastCellNum() – Get the index of the last cell contained in the row Plus one as index starts from ZERO
  3. getStringCellValue() – Get the value of the cell as a String
  4. getRow(int) – Returns the row.
  5. getCell(int) – Get the cell representing a given column
  6. getNumericCellValue() – Get the value of the cell as a number.
  7. getDateCellValue() – Get the value of the cell as a date.
  8. getBooleanCellValue() – Get the value of the cell as a boolean.

Below is the sample Excel File:

Sample Excel

We can download the Apache POI Jar files from this link and can find the screenshots below for the same.

Apache POI Binary Distribution




Apache POI Download Link

Points to Remember:

  1. Row index starts from ZERO
  2. Column index starts from ZERO
  3. Extension of excel file is ‘.xlsx’ from Excel 2007
  4. If you want to read integer value then you have to use “‘”(i.e. apostrophe) value in front of that value.[Example : 10 → ‘10]
  5. We need to use different kind of methods to read String, Integer and Date values from the excel.

Now we will write a sample stand alone program that will read the data from the excel:

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 java.io.FileInputStream;

public class ReadExcelData
{
    public static void main(String args[]) throws Exception
    {
        FileInputStream fis = new FileInputStream("/Volumes/Krishna/Jar Files/poi-3.16-beta1/TestData.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(fis);
        XSSFSheet sheet = workbook.getSheet("Credentials");
        XSSFRow row = sheet.getRow(0);

        int col_num = -1;

        for(int i=0; i < row.getLastCellNum(); i++)
        {
            if(row.getCell(i).getStringCellValue().trim().equals("UserName"))
                col_num = i;
        }

        row = sheet.getRow(1);
        XSSFCell cell = row.getCell(col_num);

        String value = cell.getStringCellValue();
        System.out.println("Value of the Excel Cell is - "+ value);
    }
}

In the above program we have hard-coded the row and column numbers in the program. But for the best practice we will create a util method and will call that method where ever we need. For this we will write 2 classes, one will have the actual logic to read the excel data and another class will call this method.



Below is the excel read data util class. In this we will write a method called “getCellData()” and it will accept 3 parameters called sheetName, columnName and rowNumber.

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.CellType;
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 java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ExcelApiTest
{
    public FileInputStream fis = null;
    public XSSFWorkbook workbook = null;
    public XSSFSheet sheet = null;
    public XSSFRow row = null;
    public XSSFCell cell = null;

    public ExcelApiTest(String xlFilePath) throws Exception
    {
        fis = new FileInputStream(xlFilePath);
        workbook = new XSSFWorkbook(fis);
        fis.close();
    }

    public String getCellData(String sheetName, String colName, int rowNum)
    {
        try
        {
            int col_Num = -1;
            sheet = workbook.getSheet(sheetName);
            row = sheet.getRow(0);
            for(int i = 0; i < row.getLastCellNum(); i++)
            {
                if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
                    col_Num = i;
            }

            row = sheet.getRow(rowNum - 1);
            cell = row.getCell(col_Num);

            if(cell.getCellTypeEnum() == CellType.STRING)
                return cell.getStringCellValue();
            else if(cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA)
            {
                String cellValue = String.valueOf(cell.getNumericCellValue());
                if(HSSFDateUtil.isCellDateFormatted(cell))
                {
                    DateFormat df = new SimpleDateFormat("dd/MM/yy");
                    Date date = cell.getDateCellValue();
                    cellValue = df.format(date);
                }
                return cellValue;
            }else if(cell.getCellTypeEnum() == CellType.BLANK)
                return "";
            else
                return String.valueOf(cell.getBooleanCellValue());
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return "row "+rowNum+" or column "+colNum +" does not exist  in Excel";
        }
    }
}

Below is a sample which will call the method from the above program to read the excel data using column number:

public class ReadExcelDataUsingUtilClass
{
    public static void main(String args[]) throws Exception
    {
        ExcelApiTest eat = new ExcelApiTest("/Volumes/Krishna/Jar Files/poi-3.16-beta1/TestData.xlsx");        
        System.out.println(eat.getCellData("Credentials","UserName",2));
        System.out.println(eat.getCellData("Credentials","PassWord",2));
        System.out.println(eat.getCellData("Credentials","DateCreated",2));
        System.out.println(eat.getCellData("Credentials","NoOfAttempts",2));
    }
}

This way we will read the excel data using column name.

Please watch youtube video for better and more understanding.



Share this post: on Twitter on Facebook

Read Data From Excel Using Column Number File Upload using AutoIT in Selenium

Related Posts

Row Count And Column Count in Excel

Excel - Java

Row Count And Column Count in Excel

WRITE DATA TO EXCEL USING COLUMN NAME

Excel - Java

Write Data To Excel Using Column Name

WRITE DATA TO EXCEL USING COLUMN NUMBER

Excel - Java

Write Data To Excel Using Column Number

Read Data From Excel Using Column Number

Excel - Java

Read Data From Excel Using Column Number

Newsletter

Recent Posts

  • TAKING WEB ELEMENT SCREENSHOT IN SELENIUMHow to Capture WebElement Screenshot in Selenium Webdriver using selenium 4
    December 15, 2019
  • How To SWAP Two Numbers in Java Without using Temp VariableHow to SWAP Two Numbers in Java Without Temp variable or Without Third variable
    December 8, 2019
  • How to Swap Two Numbers in Java with Temp VariableHow to SWAP Two Numbers in Java using Temp Variable
    December 1, 2019
  • How to Read Properties file in JavaHow to Read Data From Properties File in Java
    November 27, 2019
  • Compare two arrays in java with out inbuilt functionsHow to Compare Two Arrays in Java without built-in functions
    November 16, 2019
© Selenium Webdriver Appium Complete Tutorial 2025