excel-writer-in-java

Excel Writer in Java

Excel Writer in Java. Despite of already having our Test Automation Framework integrated with awesome Reporting tools like Allure Framework, ExtentReports etc, we still need test results to be sent out in tabular format. There are people in our teams who don’t have time to look at the reports. So, why don’t automate the report preparation and prepare these results on the fly.

Not just saving the test output in excel sheet we have great use of Excel Reader and Writer in popular Test Automation Frameworks like Keyword Driven Framework, Data Driven Framework, and Hybrid Framework. These frameworks are still used in the majority of projects where the test cases count ranges from 1000 – 5000 tests per project.

excel writer
 
 

For example in the Data Driven Framework where Tests execution is controlled by an external excel sheet. The sheet has the run modes as “Yes” or “No”, so first we need the Excel Reader to read it from the excel sheet. If the run mode is “Yes” then the test case will be executed else it will not. Once the test case is executed the run mode will be updated based on the status of the test cases. If it is passed run mode will be “No” and if it fails then “Yes” or “Retry”, based on the requirements and how the framework is designed. In this post, we are not going that deep but we will be how to update the excel sheet.

So, let’s begin.

In the previous post, Excel Reader in Java we used Apache POI dependency, which will remain the same for this tutorial, we don’t have to add any extra dependencies for Java Excel Writer.  Also, we created one ExcelReader.java . In this same java class, we are going to create another method writeIntoCell() but then the name of the class wouldn’t justify it, so let’s rename it to ExcelUtil .

Steps:
  1. The whole  Java Excel Writer is just this one statement cell.setCellValue(assignCellValue). Here the setCellValue is predefined we don’t have to develop it and assignCellValue is the value that we want to type/give to the cell (Pass or Fail).
    • public void writeIntoCell(String excelPath, String sheetName, String colName, int rowNum, String assignCellValue) {
      cell.setCellValue(assignCellValue);
      }
  2. However, to identify the required cell to which we want to put the data, we need a few things workbook, sheet, row, and cell. So let’s gather them one by one.
    • workbook = new XSSFWorkbook(excelPath);
    • sheet = workbook.getSheet(sheetName);
    • row = sheet.getRow(rowNum);
      These variables require three parameters “excelPath”, “sheetName” and “rowNum”, rowNum is the number of row which has the cell which needs to assigned value.
    • So in the end out method will look like this:
    • public void writeIntoCell(String excelPath, String sheetName, String colName, int rowNum, String assignCellValue) {
      try {
      workbook = new XSSFWorkbook(excelPath);
      } catch (IOException e1) {
      e1.printStackTrace();
      }
      sheet = workbook.getSheet(sheetName);
      row = sheet.getRow(rowNum);
      cell.setCellValue(assignCellValue);

      }

  3. Our method is almost complete. The last thing that we need now is to find out which column needs to be updated. Our column name is “Status” but which column number is this. Let’s find out.
    • for (int i = 0; i < getColCount(); i++) {
      if (getCellDataStringData(0, i).trim().equalsIgnoreCase(colName)) {
      colNum = i;
      break;
      }
      }
    • What we are doing here is that we are visiting each column up to the total columns a sheet has getColCount() and if it is equal to colName we are looking for we will break the for loop and save the colNum value. Now our method will look like this.
      public void writeIntoCell(String excelPath, String sheetName, String colName, int rowNum, String assignCellValue) {
      try {
      workbook = new XSSFWorkbook(excelPath);
      } catch (IOException e1) {
      e1.printStackTrace();
      }
      sheet = workbook.getSheet(sheetName);
      row = sheet.getRow(rowNum);
      int colNum = 0;
      for (int i = 0; i < getColCount(); i++) {
      if (getCellDataStringData(0, i).trim().equalsIgnoreCase(colName)) {
      colNum = i;
      break;
      }
      }
      cell = row.getCell(colNum);
      cell.setCellValue(assignCellValue); }
  4. Our method is ready. Now we just have to enter the value into the excel sheet, save the excel sheet and close it.
    • try {
      FileOutputStream fileOut = new FileOutputStream(excelPath, true);
      workbook.write(fileOut);
      workbook.close();
      fileOut.close();
      } catch (Exception e) {
      e.printStackTrace();
      }
  5. Finally, combine all steps, our method is ready and it will look like this:
    public void writeIntoCell(String excelPath, String sheetName, String colName, int rowNum, String assignCellValue) {
    try {
    workbook = new XSSFWorkbook(excelPath);
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    sheet = workbook.getSheet(sheetName);
    row = sheet.getRow(rowNum);
    int colNum = 0;
    for (int i = 0; i < getColCount(); i++) {
    if (getCellDataStringData(0, i).trim().equalsIgnoreCase(colName)) {
    colNum = i;
    break;
    }
    }
    cell = row.getCell(colNum);
    cell.setCellValue(assignCellValue);
    try {
    FileOutputStream fileOut = new FileOutputStream(excelPath, true);
    workbook.write(fileOut);
    workbook.close();
    fileOut.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
 
Let’s verify our code:

Now to test this excel writer, the method writeIntoCell(); . We will use a simple TestNG test. We will be feeding data to our test with the help of @dataprovider annotation.

Steps:
  1. But remember we only have APACHE POI a dependency in pom.xml. So, let’s add the below dependency. These dependencies are only required to build our test.
    <-- Need Selenium dependencies -->
    org.seleniumhq.selenium
    selenium-java 3.141.59
    
    
    <-- Need to manage webdriver -->
    io.github.bonigarcia webdrivermanager 4.4.3
    org.testng testng 7.4.0
    

     

     

  2. The next step is to create a class inside src/test/java and inside com.datadriven.excel.tests package. Let’s call this UserValidation.java
    1. Inside this class, our test will look like this.
      public class UserValidation extends BaseTest {
      String excelPath = System.getProperty("user.dir") + "/src/test/resources/userData.xlsx";
      ExcelUtil excelUtil = new ExcelUtil(excelPath, "Sheet1");

      @Test(dataProvider = "excel-data")
      public void verifyLoginCredentials(String username, String password, String status) {
      LoginPage loginPage = new LoginPage(getDriver());

      loginPage.launch();
      loginPage.enter_username(username);
      loginPage.enter_password(password);
      loginPage.click_submit_button();

      int rowNum = excelUtil.getRowNumber(excelPath, "Sheet1", username, 0);

      if (loginPage.isLoggedIn(username)) {
      excelUtil.writeIntoCell(excelPath, "Sheet1", "Status", rowNum, "Passed");
      } else {
      excelUtil.writeIntoCell(excelPath, "Sheet1", "Status", rowNum, "Failed");
      }
      }

      @DataProvider(name = "excel-data")
      public Object[][] excelDP() {
      Object[][] arrObj = getData();
      for (int i = 0; i < arrObj.length; i++)
      for (int j = 0; j < arrObj[i].length; j++)
      System.out.print(arrObj[i][j] + " ");
      return arrObj;
      }

      public String[][] getData() {
      String[][] data = null;
      try {
      int rowCount = excelUtil.getRowCount();
      int colCount = excelUtil.getColCount();
      data = new String[rowCount - 1][colCount];
      for (int i = 1; i < rowCount; i++) {
      for (int j = 0; j < colCount; j++) {
      data[i - 1][j] = excelUtil.getCellStringData(i, j);
      }
      }
      } catch (Exception e) {
      e.printStackTrace();
      }
      return data;
      }
      }
    2. The above test consists of so many other different concepts like TestNG , PageObject Model etc, which I have covered everything in the video. So, I insist you to watch that video till the end. Now if you notice we are using Excel Writer (writeIntoCell()) method with an if condition. If, login is successful then update the “Status” column from the sheet as “Pass” else update it as “Fail”.

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

If you face any issue, have any idea, or the other interesting way to implement Excel Reader and Writer let me know via comments below. I will do it hands-on and share it with you.

Tags: No tags

Add a Comment

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