How to Generate Excel in Java

Microsoft excel is a very powerful spreadsheet program created by Microsoft, and is very widely used. It provides numerous functions in addition to programming capability through which users can develop their own functions and procedures. Excel can also be integrated with other programming languages to build powerful software applications. In this tutorial we will learn a part of Java and Excel integration and see how to generate Excel in Java.

Step 1 – Creating a new Java Project

First of all, let’s create a java project with a class.

Java project and class

Step 2 – Downloading API

To generate excel in java, we need the Jxl library which does the I/O operation of the excel files.

To do that, let’s open up

On that page, click on jexcelapi and download it.

Api for Excel I/O

Step 3 – Importing the Library

Once downloaded, the next step is to import the library to our project. For that, go to eclipse, move over to the file menu and click on import.

Importing the downloaded Library

Step 4 – Giving Import Source

Select the File system directory here and click on next.

Choosing File System Directory

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.

Selecting the Library 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.

Giving Project Path

Step 7 – Adding build Path

The excel java api has now been imported in our library.

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.

Adding the library to build path

Step 8 – Code

After that, write the code in editor.

Now let’s quickly go through the code. On the headers, we included the JXL library and its write functions. In the main method, first we created a writable Workbook object and initialized it with the createWorkbook method using the filename and the path where we want to save our file.

Next we created a sheet in the excel file by using the createSheet method. Label constructor gets the position of the cell and the content of the cell, same as the Number constructor. The addCell method over here adds a label or number in the cell. And finally the write method writes the contents to the file.

Main code for Writing Operation

Step 9 – Debug

Now let’s run it and open up the location specified in the code.

Running the code

Step 10 – File generated

And we can see that a new file has been created.

Generate Excel File

And this is how java and excel can be integrated.