java-excel-reader

Java Excel Reader

We know that there are different types of Automation Testing frameworks Modular, Keyword Driven, Data Driven, and Hybrid. Among all these frameworks one thing which is common that all need an Java Excel Reader to read the data from an external excel sheet. Since it is such an important piece to be taken care of while preparing the framework, it has always been a popular question to be asked in Java Test Automation Interviews too. However, some of us can’t write it without help.

 
 
 
 
 

So, today we are going to see step by step how can we write the Java Excel Reader in Java without any help. Even, I never knew that it will be so easy but when I tried it hands-on, I couldn’t believe that it takes hardly 5-10 mins to complete the code. Within this small time frame, your excel reader code will be ready to use.

I have also recorded all the steps so that if you are stuck, you can go there come back, and again try, also I have uploaded the code which you can download execute and then try on your own. In this recording, I am explaining every step in detail so that you have answers to your all “WHYs”, “HOWs”, still you can email your queries/doubts to me or comment in the comment section below.

In this post, I will be showing you how can you develop the Java Excel Reader in such a way that you will never forget. Whether it is an interview or you want to try it hands-on. The best part is that it is similar to what we do in MS Office. Let’s see how.

For this tutorial, I am using the IntelliJ IDEA community version which is free but there is nothing less that you can’t do with this. Also, it is far better than Eclipse. The transition from Eclipse to Intellij IDEA was very quick for me, it impressed me within the first few minutes of using and then I never stopped using it. You can download it from here https://www.jetbrains.com/idea/download/. If this link is not working, go to Google and search “IntelliJ IDEA community version”.

 
Create a Java Maven Project first
  1. Go to IntelliJ IDEA and create a project a maven project.
    • Let’s name it com-datadriven-excel
    • Give groupID, same as the project name but dot-separated com.datadriven.excel
  2. Your project is created and now and you are given one pom.xml
    •  You need to add the below dependency to this pom.xml. We always copy-paste these dependencies from Maven Repository https://mvnrepository.com/, so nothing to learn here. For Excel Reader and Excel Writer, we just need the Apace POI dependency.
      <dependencies>
      <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.17</version>
      </dependency>
      </dependencies>
  3. Now you see src/main/java and inside you will also see com.datadriven.excel, so right-click on it and create one packageutils
  4.  Inside this utils package create a Java class ExcelReader.java
  5. Our project setup is done and from here onwards, we will start writing our code. No need for Selenium or WebDriver, nothing as such as of now, because we are only writing our Excel Reader first.

 

Write Excel Reader step by step:

As I mentioned above it is so simple that it works the same way as we do it in MS Office Excel.

We first need WorkBook > inside the workbook we have a sheet > and inside the sheet we have data.

So, in the same way, we are going to proceed with Excel.

 
Steps:
    1. Create the following variable inside the class.
      • It will look like this
      • public class ExcelReader {
        static XSSFWorkbook workbook;
        static XSSFSheet sheet;
        }
    1.  
    2. Write a constructor – Press Ctrl + n in Windows and Command + n in Mac to get the Menu. Choose Constructor and it is ready.
      • This constructor needs two parameters one is the path of the excel from the resources folder and the name of the sheet that you want to fetch the data from.
      • After that, as we discussed we will first need the Workbook and then Sheet. So, initialize both the variables
      • It will look like this:
        public class ExcelReader {
        static XSSFWorkbook workbook;
        static XSSFSheet sheet;
        public ExcelReader(String excelPath, String sheetName) {
        try {
        workbook = new XSSFWorkbook(excelPath);
        sheet = workbook.getSheet(sheetName);
        } catch (Exception e) {
        e.printStackTrace();
        }
        }

      Now we have both WorkBook and Sheet. If you notice
      sheeet
      variable was created with the help of `workbook` which makes sense when we MS Excel manually. We always create a workbook first and then create a sheet inside it.

    3. Let find out how many rows are there in the sheet (not workbook). So it will look like this. This method getPhysicalNumberOfRows() is available out of the box with the POI Apache dependency we don’t have to write it.
      • public int getRowCount() {
        return sheet.getPhysicalNumberOfRows();
        }
    4. And similarly how many Columns
      • public int getColCount() {
        return sheet.getRow(0).getPhysicalNumberOfCells();
        }
    5. As per the flow Workbook > Sheet > Row and Col > Cells Data. Now we need to fetch the data from cells. So let’s imagine that cells can have numerical data.
      • public double getCellDataNumericalValue(int rowNum, int colNum) {
        try {
        return sheet.getRow(rowNum).getCell(colNum).getNumericCellValue();
        } catch (Exception e) {
        System.out.println("There is an exception, so returning the default value as");
        e.printStackTrace();
        return 0;
        }
        }
      • So it is clear that cells are inside the sheet, so obviously we will be needing sheet variables to fetch the cell’s value, and to locate a cell we need to know row and column. In the last part, getNumericCellValue() this method always looks for a value that is double if not it will throw an error. We need this because if by mistake we have entered the wrong value it will use the proper Exception. Please see the video for a better understanding.

    6. Just like we fetched a numeric value from a cell. We need a method that can fetch/read a `String` value and that will be:
      •  Basically, if you notice it is the same method (without try-catch block), it is just that we are converting the value to String using .toString() method
      • public String getCellDataStringData(int rowNum, int colNum) {
        return sheet.getRow(rowNum).getCell(colNum).toString();
        }
      • That’s it our Java Excel Reader is ready. Now we only want to test it, whether it is working fine or not.
         public class ExcelReader {
        
            static XSSFWorkbook workbook;
        static XSSFSheet sheet;

        public ExcelReader(String excelPath, String sheetName) {
        try {
        workbook = new XSSFWorkbook(excelPath);
        sheet = workbook.getSheet(sheetName);
        } catch (Exception e) {
        e.printStackTrace();
        }
        }

        public int getRowCount() {
        return sheet.getPhysicalNumberOfRows();
        }

        public int getColCount() {
        return sheet.getRow(0).getPhysicalNumberOfCells();
        }

        public double getCellDataNumericalValue(int rowNum, int colNum) {
        try {
        return sheet.getRow(rowNum).getCell(colNum).getNumericCellValue();
        } catch (Exception e) {
        System.out.println("There is an exception, so returning the default value as");
        e.printStackTrace();
        return 0;
        }
        }

        public String getCellDataStringData(int rowNum, int colNum) {
        return sheet.getRow(rowNum).getCell(colNum).toString();
        }
        }
    7. Now for testing, let’s create another class where we will only put our test cases. Go to src/test/java and create one package tests inside com.datadriven.excel
    8. Inside this this tests package, create one Java file as FetchData.java which will look like this.
      public class FetchData {
      static String excelPath = System.getProperty("user.dir") + "/src/test/resources/Book1.xlsx";
      static ExcelReader excelReader = new ExcelReader(excelPath, "Sheet1");

      public static void main(String[] args) {
      int rowCount = excelReader.getRowCount();
      int colCount = excelReader.getColCount();
      double cellNumValue = excelReader.getCellDataNumericalValue(1, 2);
      String cellStringValue = excelReader.getCellDataStringData(1, 2);
      System.out.println("Row count is " + rowCount);
      System.out.println("Col count is " + colCount);
      System.out.println("Double value is " + cellNumValue);
      System.out.println("String value is " + cellStringValue);
      }
      }

 
Verify that your Excel Reader is working fine.

To verify that Excel Reader is working fine or not, you can test with a different set of test data. For example, you can change the value of the cell (1,2) and make it a String and run the test. You must get an exception this time because the method getCellDataNumericalValue() is expecting a numerical value there.

That’s it for today, I hope it will help in implementing, designing your own data-driven framework.

 

For the post on Excel Writer in Java click here. This post also has a recording. In this post, I will be taking an example of an application that has 10 user credentials and we have to update the excel sheet with pass & fail status. I am sure it is going to be very interesting and you will like it

excel writer
Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *