How to Create Pivot Table in Excel using Java?
Last Updated :
06 Dec, 2023
A pivot table is needed to quickly analyze data of a table with very little effort (and no formulas) and sometimes not everyone has time to look at the data in the table and see what’s going on and use it to build good-looking reports for large data sets in an Excel worksheet. Let's discuss a step-by-step proper explanation to create a pivot table in an Excel file in Java using Free Spire.XLS for Java API.
Requirements to Create Pivot Table in Excel using Java
Firstly, we need to add necessary dependencies to the Maven project including the Free Spire.XLS project before starting to write the code.
How to Install Spire.XLS for Java
By adding the following code to your project's pom.xml file, you can quickly import the JAR file into your program if you use Maven.
XML
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version> </dependency>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>Â Â Â
How to Create a Pivot Table in Excel using Java
Here are the steps for using Java to make a pivot table in Excel.
Step 1: Create a workbookÂ
Workbook workbook = new Workbook();
Step 2: Create a sheetÂ
Worksheet sheet = workbook.getWorksheets().get(0);
Step 3: Add some data to the worksheet in table form.
sheet.getCellRange("A1").setValue("Student Name");
Step 4: Pivot Cache is something that automatically gets generated when you create a Pivot Table. Create an object of PivotCache and add a range.
PivotCache cache = workbook.getPivotCaches().add(dataRange);
Step 5: Create an object of PivotTable to get PivotTable and add table name, Cell Range from where a table is starting to arg1, PivotCache arg2
PivotTable pivotTable = sheet.getPivotTables().add("Pivot Table", sheet.getCellRange("A16"), cache);
Step 6: Create a pivot field to configure the pivot table's fields after that set layout of the pivot table by using the set Axis method and then select type.Â
PivotField pivotField1 = null;
if (pivotTable.getPivotFields().get("Student Name") instanceof PivotField) {
 pivotField1 = (PivotField) pivotTable.getPivotFields().get("Student Name");
 }
 pivotField1.setAxis(AxisTypes.Row);
Step 7: Drag the field to the data area
pivotTable.getDataFields().add(pivotTable.getPivotFields().get("Attendance"), "SUM of Attendance", SubtotalTypes.Sum);
Step 8: Set PivotTable style
pivotTable.setBuiltInStyle(PivotBuiltInStyles.PivotStyleMedium12);
Step 9: Calculate the data
pivotTable.calculateData();
Step 10: Set column width with setColumnWidth method having two parameters, first is columnIndex in int datatype, width size in double datatype.
sheet.setColumnWidth(1, 14);
sheet.setColumnWidth(2, 14);
Step 11: Save workbook by using saveToFile(String fileName, ExcelVersion version)
workbook.saveToFile(workbookName, ExcelVersion.Version2013);
How to write a Java Program to create a pivot table in a spreadsheet
Java
import com.spire.xls.AxisTypes;
import com.spire.xls.CellRange;
import com.spire.xls.ExcelVersion;
import com.spire.xls.PivotBuiltInStyles;
import com.spire.xls.PivotCache;
import com.spire.xls.PivotField;
import com.spire.xls.PivotTable;
import com.spire.xls.SubtotalTypes;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
class GFG {
public static void main(String[] args)
{
// Create a workbook
Workbook workbook = new Workbook();
// Create a sheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Add data to the worksheet in table form
// Header
sheet.getCellRange("A1").setValue("Student Name");
sheet.getCellRange("B1").setValue("Month");
sheet.getCellRange("C1").setValue("Attendance");
// Data
sheet.getCellRange("A2").setValue("Harry");
sheet.getCellRange("A3").setValue("Harry");
sheet.getCellRange("A4").setValue("Harry");
sheet.getCellRange("A5").setValue("Nicole");
sheet.getCellRange("A6").setValue("Nicole");
sheet.getCellRange("A7").setValue("Nicole");
sheet.getCellRange("A8").setValue("Peter");
sheet.getCellRange("A9").setValue("Peter");
sheet.getCellRange("A10").setValue("Peter");
sheet.getCellRange("A11").setValue("Lisa");
sheet.getCellRange("A12").setValue("Lisa");
sheet.getCellRange("A13").setValue("Lisa");
sheet.getCellRange("B2").setValue("January");
sheet.getCellRange("B3").setValue("February");
sheet.getCellRange("B4").setValue("March");
sheet.getCellRange("B5").setValue("January");
sheet.getCellRange("B6").setValue("February");
sheet.getCellRange("B7").setValue("March");
sheet.getCellRange("B8").setValue("January");
sheet.getCellRange("B9").setValue("February");
sheet.getCellRange("B10").setValue("March");
sheet.getCellRange("B11").setValue("January");
sheet.getCellRange("B12").setValue("February");
sheet.getCellRange("B13").setValue("March");
sheet.getCellRange("C2").setValue("25");
sheet.getCellRange("C3").setValue("22");
sheet.getCellRange("C4").setValue("24");
sheet.getCellRange("C5").setValue("24");
sheet.getCellRange("C6").setValue("23");
sheet.getCellRange("C7").setValue("24");
sheet.getCellRange("C8").setValue("22");
sheet.getCellRange("C9").setValue("15");
sheet.getCellRange("C10").setValue("23");
sheet.getCellRange("C11").setValue("25");
sheet.getCellRange("C12").setValue("20");
sheet.getCellRange("C13").setValue("18");
// Add a PivotTable to the worksheet
// Get Range of Table
CellRange dataRange = sheet.getCellRange("A1:C13");
PivotCache cache
= workbook.getPivotCaches().add(dataRange);
PivotTable pivotTable = sheet.getPivotTables().add(
"Pivot Table", sheet.getCellRange("A16"),
cache);
// Drag the fields to the row area
PivotField pivotField1 = null;
if (pivotTable.getPivotFields().get("Student Name")
instanceof PivotField) {
pivotField1
= (PivotField)pivotTable.getPivotFields()
.get("Student Name");
}
pivotField1.setAxis(AxisTypes.Row);
PivotField pivotField2 = null;
if (pivotTable.getPivotFields().get("Month")
instanceof PivotField) {
pivotField2
= (PivotField)pivotTable.getPivotFields()
.get("Month");
}
pivotField2.setAxis(AxisTypes.Row);
// Drag the field to the data area
pivotTable.getDataFields().add(
pivotTable.getPivotFields().get("Attendance"),
"SUM of Attendance", SubtotalTypes.Sum);
// Set PivotTable style
pivotTable.setBuiltInStyle(
PivotBuiltInStyles.PivotStyleMedium12);
// Calculate data
pivotTable.calculateData();
// Set column width
sheet.setColumnWidth(1, 14);
sheet.setColumnWidth(2, 14);
// Save the result file
String workbookName = "Geeks_For_Geeks.xlsx";
workbook.saveToFile(workbookName,
ExcelVersion.Version2013);
System.out.println(workbookName
+ " is written successfully");
}
}
Output
On the console window
When the program is successfully executed.
Geeks_For_Geeks.xlsx is written successfully
Output
Workbook (Excel file)

Similar Reads
How to Create Pivot Chart from Pivot Table in Excel using Java?
A Pivot Chart is used to analyze data of a table with very little effort (and no formulas) and it gives you the big picture of your raw data. It allows you to analyze data using various types of graphs and layouts. It is considered to be the best chart during a business presentation that involves hu
4 min read
How to Create a Power PivotTable in Excel?
When we have to compare the data (such as name/product/items, etc.) between any of the columns in excel then we can easily do with the help of Pivot table and pivot charts. But it fails when it comes to comparing those data which are in two different datasets, at that time Power Pivot comes into rol
4 min read
How to Create a Formula in Excel using Java?
Apache POI is a popular open-source Java library that provides programmers with APIs for creating, modifying, and editing MS Office files. Excel is very excellent at calculating formulas. And perhaps most Excel documents have formulas embedded. Therefore, itâs trivial that on a fine day, you have to
3 min read
How to Create Relational Tables in Excel?
Excel directly doesn't provide us ready to use a database, but we can create one using relationships between various tables. This type of relationship helps us identify the interconnections between the table and helps us whenever a large number of datasets are connected in multiple worksheets. We ca
4 min read
How to Flatten Data in Excel Pivot Table?
Flattening a pivot table in Excel can make data analysis and extraction much easier. In order to make the format more usable, it's possible to "flatten" the pivot table in Excel. To do this, click anyplace on the turn table to actuate the PivotTable Tools menu. Click Design, then Report Layout, and
7 min read
How to Create Formula Cell in Excel Sheet using Java and Apache POI?
In the previous article, we have seen how to read data from the formula cell, here we are going to create the formula cell using Apache POI. Â In this article, we are creating an Excel file with three columns consisting of values and the last column is the formula cell which is calculated from the o
2 min read
How to Sort a Pivot Table in Excel : A Complete Guide
Sorting a Pivot Table in Excel is a powerful way to organize and analyze data effectively. Whether you want to sort alphabetically, numerically, or apply a custom sort in Excel, mastering this feature allows you to extract meaningful insights quickly. This guide walks you through various Pivot Table
7 min read
How to Remove Pivot Table But Keep Data in Excel?
In this article, we will look into how to remove the Pivot Table but want to keep the data intact in Excel. To do so follow the below steps: Step 1: Select the Pivot table. To select the table, go to Analyze tabSelect the menu and choose the Entire Pivot Table. Step 2: Now copy the entire Pivot tabl
1 min read
How to Hide Zero Values in Pivot Table in Excel?
One of Microsoft Excel's most important features is the pivot table. You might be aware of this if you have worked with it. It provides us with a thorough view and insight into the dataset. You can do a lot with it. The pivot table might include zero values. In this lesson, you will learn how to hid
5 min read
How to Rotate Pie Charts in Excel?
A Pie Chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportion.In this article, we'll see how we can create and rotate pie charts. How to make Pie Charts in Excel ? Follow the below steps to create a pie chart in Excel: Step 1: Formatting data for pie
2 min read