Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Read Excel File In Java

Java Excel API is a mature, open source java API enabling developers to read, write, and modify Excel spreadsheets dynamically. Here we explain how to read an excel file using jxl library. You create a maven based project and add jxl library dependency in the pom.xml file. 

 

<dependency>
	<groupId>net.sourceforge.jexcelapi</groupId>
	<artifactId>jxl</artifactId>
	<version>2.6.12</version>
</dependency>

Write the following code in the java class file "ReadExcelFile.java".

package com.example.excel;

import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*;

import java.io.File;
import java.io.IOException;

public class ReadExcelFile {
    public static void main(String[] args) throws WriteException {
        try {
            //define workbook
            Workbook workbook = null;
            try {
                //initialize work book to read
                workbook = Workbook.getWorkbook(new File("output.xls"));
            } catch (BiffException e) {
                e.printStackTrace();
            }
            //get first sheet
            Sheet sheet = workbook.getSheet(0);
            //print first sheet name
            String sheetName=sheet.getName();
            System.out.println("Sheet name :"+sheetName);
            //define cell string or number variable
            String cellString = null;
            double cellNumber = 0;
            //loop through each cell and read content
            for(int row=0;row<2;row++) {
                for (int col = 0; col < 7; col++) {
                    Cell cell = sheet.getCell(col, row);
                    if (cell.getType() == CellType.LABEL) {
                        cellString = cell.getContents();
                        System.out.print(cellString + " ,");
                    } else if (cell.getType() == CellType.NUMBER) {
                        NumberCell nc = (NumberCell) cell;
                        cellNumber = nc.getValue();
                        System.out.print(cellNumber + " ,");
                    }

                }
                //start new line for new row
                System.out.println();
            }
            //close work book
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Run the code above. An excel file "output.xls" is created with the following content. 

Sheet name :TestCases
TestId ,TestName ,TestModule ,TestType ,TestSteps ,TestResult ,Note ,
1234.0 ,Login ,Dashboard ,Regression ,1 ,Open Browser , ,