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. 



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

package com.example.excel;

import jxl.*;
import jxl.write.*;


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) {
            //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
            //close work book
        } catch (IOException e) {

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 , ,