Open In App

How to Create Pivot Chart from Pivot Table in Excel using Java?

Last Updated: 06 Dec, 2023

N

Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 huge data. To add a pivot chart to an Excel worksheet, you need to use the “WorksheetChartsCollection.add” method. 

Before Creating a Pivot Chart, one first needs to go through how to Create Pivot Table in Excel using Java. Now let’s discuss the steps to create a pivot chart in an Excel file in Java using Free Spire.XLS for Java API.

How to Create a Pivot Table in Excel using Java

Step 1: Load the Excel file

Workbook workbook = new Workbook()

String workbookName = “Geeks_For_Geeks.xlsx”;

workbook.loadFromFile(workbookName);

Step 2: Get the first worksheet

Worksheet sheet = workbook.getWorksheets().get(0);

Step 3: Get the first pivot table in the worksheet

IPivotTable pivotTable = sheet.getPivotTables().get(0);

Step 4: Add a clustered column chart based on the pivot table to the second worksheet

Chart chart = workbook.getWorksheets().get(1).getCharts().add(ExcelChartType.ColumnClustered, pivotTable);

 Step 5: Set chart position

chart.setTopRow(2);

chart.setBottomRow(15);

 Step 6: Set chart title

chart.setChartTitle(“Total”);

Step 7: Save the result file

workbook.saveToFile(workbookName, ExcelVersion.Version2013);

Let’s write a Java Program to create a pivot chart from a pivot table in a spreadsheet.

Java




import com.spire.xls.*;
import com.spire.xls.core.IPivotTable;
 
class GFG {
    public static void main(String[] args)
    {
        // Load the Excel file
        Workbook workbook = new Workbook();
        String workbookName = "Geeks_For_Geeks.xlsx";
        workbook.loadFromFile(workbookName);
 
        // 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 to the second worksheet
        Chart chart
            = workbook.getWorksheets()
                  .get(1)
                  .getCharts()
                  .add(ExcelChartType.ColumnClustered,
                       pivotTable);
       
        // Set chart position
        chart.setTopRow(2);
        chart.setBottomRow(15);
       
        // Set chart title
        chart.setChartTitle("Total");
 
        // Save the result file
        workbook.saveToFile(workbookName,
                            ExcelVersion.Version2013);
        System.out.println(workbookName
                           + " is written successfully");
    }
}


Output

On the console window when the program is successfully executed.

GeeksForGeeks.xlsx is written successfully.

Output

On the Workbook (Excel file)

Create Pivot Chart from Pivot Table in Excel using Java

Conclusion

Creating a Pivot chart from a pivot table in Excel using Java can greatly improve data analysis and visualization. By programmatically generating pivot tables and charts with Apache POI, you can automate repetitive tasks and efficiently handle large datasets. This article provides you step by step implementation of how to create a pivot chart in Excel using Java.

FAQs on How to Create Pivot Chart from Pivot Table in Excel using Java

Q1: What is the need for creating a Pivot chart from a Pivot table in Excel using Java?

Answer:

Creating a pivot chart from the pivot table using Java and Apache POI offers several advantages. It allows you to automate the process of generating Pivot charts, saving you time and effort. Java flexibility enables handling large datasets and enhancing data analysis capabilities.

Q2: How to create a Pivot chart from the pivot table in Excel using Java and Apache POI?

Answer:

After creating a Pivot table, Follow the below steps to create a Pivot Chart:

Step 1: Open the Existing Workbook with the Pivot table.

Step 2: Create a new sheet to hold the Pivot Chart.

Step 3: Define the top-left corner of the Pivot Chart on the new sheet.

Step 4: Draw the Pivot Chart using the Drawing canvas.

Step 5: Set the Pivot table as the data source for the pivot chart.

Q3: Can we customize the Pivot Chart appearance and layout using Java and Apache POI?

Answer:

Yes, you can customize the Pivot Chart appearance and layout using various methods provided by Apache POI. You can change chart titles, axis labels, colors, chart type, and many other properties to create a visually appealing Pivot chart.

Q4: Can I use other libraries or tools instead of Apache POI to create Pivot charts in Excel using Java?

Answer:

Yes, there are other libraries and tools available that allow working with Excel files and charts in Java, such as Apache POI -HSSF, Apache POI-XSSF, JExcelAPI, and Java Excel API(JXL).



N

News
Improve
Discuss
Practice
Do you want to advertise with us?Click here to know more

C

Table and Chart Combinations in Excel Power Pivot

For data exploration, visualization, and reporting, Power Pivot offers a variety of Power PivotTable and Power PivotChart combinations. A Power PivotChart is a PivotChart that was made using the Power Pivot window and is based on the Data Model. Despite sharing certain functionality with Excel PivotChart, it offers additional features that give it greater strength. You will discover how to build the Table and Chart combinations from the Power Pivot window in this article. Creating a Pivot Chart and Table in Excel Step 1: Let's take a dataset as an example in order to understand the Pivot chart and table. This is the major dataset that will be used in this case. Step 2: Select the data. Navigate to the insert tab on the top of the ribbon then in the charts group select Pivot Chart and then PivotChart & Pivot Table. Step 3: Create a PivotTable dialog box appear. Here select a table or range and a select new worksheet and then click OK. Step 4: Now as you can see pivot table is created and the PivotTable Fields pane appears. Step 5: Now in the PivotTable Fields pane drag the month's field to the Axis area and the Sales field to the values area. Step 6: Now as you can see after sel
Read More

How to Create Pivot Table in Excel using Java?

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 JavaFirstly, 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 JavaBy 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> <dep
Read More

I

How to Group and Ungroup Pivot Chart Data Items in Excel?

A pivot chart is the visual representation of a pivot table in Excel. Pivot charts and pivot tables are connected with each other. Pivot chart are much more flexible than normal chart because Pivot Chart is linked to a PivotTable. Filters, sorts, and data rearrangements applied to Pivot Table are reflected on the chart. Steps to create Pivot chart : Follow the below steps to create a Pivot chart: Select the table to create the pivot chart.Inside Insert tab, click Pivot chart.A dialog box will appear, select the table and the cell where you want the table and chart.Both Pivot chart and Table will be created, but no field is selected.Select the fields, you want in the chart.Chart will be formed.To Group data in the Chart: Follow the below steps to group data in the Chart: Select the rows or columns from the table, you want to group.Right-click and press group.The data will be grouped and the chart will show those rows together along with the Group name.To Ungroup data in the Chart : Follow the below steps to ungroup data in the chart: Select the group name.Right-click and press Ungroup.The data items in both the table and chart will be ungrouped.
Read More

Creating a Power Pivot Chart in Excel

article_img
Power Pivot is an Excel add-in that is available for Excel 2021, Excel 2019, Excel 2016, and Excel 2013. Power Pivot is used to create data models and performs high-level data analysis to establish relationships and give results easily. Power pivot can analyze large data rapidly and creates data models by building extensive relationships and calculations based on the given data. Creation of Power Pivot Chart Let's create a chart using Power Pivot on the following data model. Step 1: Click the Home tab, which is visible above, and click on the pivot table Step 2: Then click on the pivot chart. Then a dialog box appears. Select a new worksheet and click ok. Then it will appear like the image below, which contains all the table names in pivot chart fields. Step 3: Then click on the pivot chart fields (which contain table values) that represent the chart. So by clicking these fields, the chart will appear according to their relation. These are called value field buttons. Based on the data in these field buttons, the chart is prepared. This is called a Legend. In this area sum of values is given. We can remove the legend and value field buttons. The icon at the left side
Read More

R

Creating a Gantt Chart With Milestones Using a Stacked Bar Chart In Excel

article_img
One of the most common and effective methods of displaying activities (tasks or events) plotted against time is a Gantt chart, which is frequently used in project management. On the left side of the chart is a list of the activities, and at the top is a suitable time scale. A bar is used to symbolize each activity, and the location and length of the bar correspond to the activity's beginning, middle, and finish dates. The following elements are crucial to any effective Gantt chart: The task list, which can be divided into groups and subgroups, runs vertically along the left side of the Gantt chart to define project activity.Timeline: Displays months, weeks, days, and years horizontally across the top of the Gantt chart.Dateline: On a Gantt chart, a vertical line displays the current date.Bars: On the right side of the Gantt chart, horizontal markers indicate tasks and display status, length, and start and finish dates.Milestones: Yellow diamonds that identify significant occasions, dates, choices, and outputsDependencies are thin grey lines connecting activities that must occur in a specific order.The percentage of work that has been completed or the color of the bars can be used t
Read More

Radar Chart or Spider Chart in Excel

article_img
Radar Chart is a pictorial representation of multivariate data. Multivariate data analysis in statistics is nothing but dealing with more than one outcome or observations. Radar graphs can be of two dimensions, three dimensions, or more on the basis of the multiple comparable variables used. The variables are represented on the axis starting from the same points with equal intervals on the axes. The number of axes in a radar graph solely depends on the number of variables used. The Radar Chart has various other names like spider chart, web chart, spider web chart, cobweb chart, irregular polygon, star chart, Kiviat Diagram, etc. The data from the observations in the form of tables are plotted on each axis and by joining all these points in the axes a polygon type structure is formed. So, the number of polygons is dependent on the number of observations. In this article, we will see how to plot a Radar Chart in Microsoft Excel for a given data set using two examples. Example 1 : Consider the table shown below which consists of the data of two Geek students who enrolled in our various courses. Our mentors have rated them on the basis of the student's performance in the individual
Read More

How to Flatten Data in Excel Pivot Table?

article_img
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 then, at that point, Show in Tabular Form. This will isolate the line names and make it simpler to investigate information.What Does Flattening Mean in Excel?Flattening a pivot table in Excel refers to transforming the data from a pivot table format, which can be complex and hierarchical, into a simple tabular format. This process separates row labels and creates a structure that is easier to work with for further analysis or export to data warehouses.Flatten is a table function that takes a VARIANT, OBJECT, or ARRAY column and produces a lateral view (for example an inline view that contains a relationship alluding to different tables that go before it in the FROM clause). FLATTEN can convert semi-structured data to a relational representation.Benefits of Flattening Data in ExcelImproved Data Analysis: Flattened data is easier to analyze, as all relevant information is available in a ta
Read More

How to Add and Use an Excel Pivot Table Calculated Field?

article_img
Excel pivot tables are one of its most helpful features. They are utilized to summarize or aggregate large quantities of data. The data can be summarized using the average, the count, or other statistical approaches. It summarizes a large amount of data into a few rows and columns. They make it simple to explore the data from various views and angles and are excellent for data exploration. When you create a Pivot table, you often need to add more data and calculations to your analysis. If you require a new data point that can be obtained by leveraging existing data points in the Pivot Table, you don't need to go back and add it to the source data. Instead, you can utilize a Pivot Table Calculated Field to accomplish this. Pivot Table Calculated Field The "Pivot Table calculated field" option allows you to insert more data or calculations in the pivot table. For our reports, we frequently need to include our own unique calculations that can relate to other fields in the data collection. Benefits of using a Pivot Table Calculated FieldIt is scalable since it will automatically account for any new data added to your Pivot Table. You can utilize a Calculate Field in your Pivot Table ju
Read More

C

How to Hide Zero Values in Pivot Table in Excel?

article_img
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 hide zero values in the pivot table using relevant examples and visuals. Hide the rows in a pivot table that have zero values. After concealing the zero-value rows, your pivot table will seem neater and the data will be suppressed. How to Hide Zero Values in Pivot Table in Excel? ImplementationLet's take a dataset as an example to understand How to Hide Zero Values in a Pivot Table in Excel. This is the dataset that we are going to use in this scenario. The Excel table has some zero values, as you can see. First, you must transform an excel table into a pivot table. You may need to hide them at times to have a clear view of the pivot table. Methods for Hiding Zero-ValuesThere are three different methods for hiding zero values in an Excel pivot table. Table of Content How to Create a Filter Field to Hide Rows with Zero ValuesHow to Hide Pivot Table Zero Values Using Excel's Format Cells Comm
Read More

How to Troubleshoot and Fix Excel Pivot Table Errors?

article_img
Power Pivot is an Excel add-in, a data modeling technology that helps the user to create data models, establish relationships, and create calculations. However, it is possible to encounter a few errors during the process. here in this article, we will discuss some of the Excel Pivot Table Errors that may occur and how we can fix them. Usually, Excel Pivot works smoothly and efficiently, however, it is inevitable to encounter some errors while working with the software. Here are some of the common errors that users might encounter during working with Excel PowerPivot. "Unable to load the Data Model" Error Sometimes, A simple data change, for example, adding the pivot table data to the Data Model may cause a pivot table refresh error. It’s not that common, however, sometimes users do face such issues. As we can see in the image below: Here, in the image, as we can see above the message is showing that the “PowerPivot is unable to load the Data Model”. Solution: The change from the UPPER case to the PROPER case or other similar changes in the source data headings may be the primary cause of this error resulting in the data model having a second instance of the field. As shown in t
Read More
three90RightbarBannerImg