Create Excel File using Java

As a powerful data visualization and analysis tool, Excel is the widely used in various fileds of work and research. This article will give a simple example of how to create an Excel file programatically with a free Java Excel class library.

Installation (2 Method)
1# Download the free API (Free Spire.XLS for Java)and unzip it, then add the Spire.Xls.jar file to your project as dependency.

2# You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.


Code Snippet

import com.spire.xls.*;

import java.awt.*;

public class CreateExcel {
public static void main(String[] args){
//Create a Workbook instance
Workbook workbook = new Workbook();

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Set name for the first worksheet
sheet.setName("Data Sheet");

//Create a CellStyle for header cells
CellStyle style1 = workbook.getStyles().addStyle("Header Style");

//Create a CellStyle for data cells
CellStyle style2 = workbook.getStyles().addStyle("Data Style");

//Add data and apply style for header cells
for (int column=1; column<5; column++)
CellRange header =sheet.getCellRange(1,column);
header.setValue("Column " + column );

// Add data and apply style for data cells
for (int row=2; row<11; row++)
for (int column=1; column<5; column++)
CellRange cell = sheet.getCellRange(row, column);
cell.setValue("Data " + row + ", " + column);

//Save the resultant file
workbook.saveToFile("CreateExcel.xlsx", FileFormat.Version2013);

A screenshot of the generated Excel document:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store