Microsoft Excel can be integrated with other programming languages to build powerful software applications. In this tutorial we will learn how to integrate Java with excel to read excel file in java.
Step 1 – Creating a new Java Project
For that we have created a new java project in eclipse named “Open Excel File” and a class “ReadExcel” in the package reader.
Step 2 – Downloading API
To read excel file in java we need the Jxl library which does the I/O operation of the excel files.
So, to download that API, let’s open up www.sourceforge.net/projects/jexcelapi/files/jexcelapi/2.6.12
On that page, click on jexcelapi and download it.
Step 3 – Importing the Library
Now the next step is to import the library to our project. For that, go to eclipse, move over file and click on Import.
Step 4 – Giving Import Source
Select the File System directory here and click on next.
Step 5 – Giving the Library Path
Now let us locate the JXL library which we have just downloaded
After locating the file, we have to select the jxl.jar file.
Step 6 – Inserting Library into the project
After that done, we have to browse and select our project where we want to import the library.
Step 7 – Finalizing the import
With all that taken care of, we just have to click on Finish.
After that we can see the JXL.jar in our project explorer.
Step 8 – Adding in build Path
After that we have to Right click on the library icon, hover over to build path and Click on the Add to build Path option.
Step 9 – Code
Now let’s go through the code.
First we open the file using file descriptor FILE. Then we create a workbook object to access the excel file.
The getSheet method allows us to access the sheet of the workbook. The getColumn and getRows method returns the column and rows of the file and the getContent method returns the content of the file.
Step 10 – Inside Main
Let us move on to Main.
We are creating an object test of our class. In the setInputFile method, we have to give the path of the excel file we want to read.
As written here our excel file is in the E drive named excel.xls. In this file, we have some labels written.
Step 11 – Debug
So now, let’s run the program.
After running the code, we will get the contents of the file in console.
And this is how we can read excel file in java.