Create Pivot Chart in Excel using Java

codesharing

CodeSharing

Posted on March 12, 2021

Create Pivot Chart in Excel using Java

In my previous posts, I've introduced how to create an Excel pivot table with the 3rd party library--Free Spire.XLS for Java. This article will demonstrates how to create a pivot chart based on the data in pivot table.

Installation
Method 1: Download the Free Spire.XLS for Java and unzip it, then add the Spire.Xls.jar file to your project as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.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>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>3.9.1</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Java Code:

import com.spire.xls.*;
import com.spire.xls.core.IPivotTable;

public class CreatePivotChart {
    public static void main(String[] args) {
        //Load the Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("data.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);
        //get the first pivot table in the worksheet
        IPivotTable pivotTable = sheet.getPivotTables().get(0);

        //Add a clustered column chart based on the pivot table data
        Chart chart = sheet.getCharts().add(ExcelChartType.ColumnClustered, pivotTable);
        //Set chart position
        chart.setTopRow(14);
        chart.setBottomRow(25);
        //Set chart title
        chart.setChartTitle("Total");

        //Save the result file
        workbook.saveToFile("CreatPivotChart.xlsx", ExcelVersion.Version2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

💖 💪 🙅 🚩
codesharing
CodeSharing

Posted on March 12, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related