Data visualization is crucial for transforming raw data into actionable insights, and Excel's pie and doughnut charts are excellent tools for representing proportions and compositions. While manually creating these charts can be tedious, especially with dynamic data, programmatic generation offers efficiency and automation. This tutorial will guide you through creating both pie and doughnut charts in Excel using Spire.XLS for Java, a powerful library designed for Excel manipulation. You'll learn to create a pie chart in Excel and create a doughnut chart in Excel with ease.
Introduction to Spire.XLS for Java & Installation
Spire.XLS for Java is a professional API that enables Java applications to create, read, write, and convert Excel documents without requiring Microsoft Excel to be installed on the system. It supports a wide range of Excel features, including charts, formulas, data validation, and more, making it an invaluable tool for developers looking to automate Excel tasks.
To integrate Spire.XLS for Java into your project, you'll typically add it as a Maven dependency. Here's how to do it:
Download the JAR file from the official E-iceblue website or use Maven.
Add the Maven dependency to your pom.xml file:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>15.10.5</version>
</dependency>
</dependencies>
Note: Replace 13.4.1 with the most recent version available on the E-iceblue website.
How to Create a Pie Chart in Excel with Java
Creating a pie chart involves preparing your data, adding a chart to a worksheet, specifying the chart type, and then configuring its data source and appearance.
Here’s a step-by-step guide to create a pie chart in Excel using Spire.XLS for Java:
- Initialize a Workbook: Create a new Workbook object and get the first Worksheet.
- Add Data to Worksheet: Populate cells with the data that will be used for the pie chart. This typically includes categories and their corresponding values.
-
Add a Chart: Use the
Worksheet.getCharts().add()method to add a new chart, specifyingExcelChartType.Pie. -
Set Chart Data Range: Specify the range of cells that contain the data for the chart using
setDataRange()andsetSeriesDataFromRange()for pie charts as data is usually one series. -
Set Chart Position: Define the location and size of the chart on the worksheet using
setLeftColumn,setTopRow,setRightColumn, andsetBottomRow. -
Set Chart Title: Assign a title to the chart using
setChartTitle(). - Save the Workbook: Save the workbook to an Excel file.
import com.spire.xls.*;
import com.spire.xls.charts.ChartSerie;
import java.awt.*;
public class CreatePieChart {
public static void main(String[] args) {
//Create a Workbook object
Workbook workbook = new Workbook();
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Insert data to specified cells
sheet.getCellRange("A1").setValue("Year");
sheet.getCellRange("A2").setValue("2002");
sheet.getCellRange("A3").setValue("2003");
sheet.getCellRange("A4").setValue("2004");
sheet.getCellRange("A5").setValue("2005");
sheet.getCellRange("B1").setValue("Sales");
sheet.getCellRange("B2").setNumberValue(4000);
sheet.getCellRange("B3").setNumberValue(6000);
sheet.getCellRange("B4").setNumberValue(7000);
sheet.getCellRange("B5").setNumberValue(8500);
//Set cell styles
sheet.getCellRange("A1:B1").setRowHeight(15);
sheet.getCellRange("A1:B1").getCellStyle().setColor(Color.darkGray);
sheet.getCellRange("A1:B1").getCellStyle().getExcelFont().setColor(Color.white);
sheet.getCellRange("A1:B5").getCellStyle().setVerticalAlignment(VerticalAlignType.Center);
sheet.getCellRange("A1:B5").getCellStyle().setHorizontalAlignment(HorizontalAlignType.Center);
//Set number format
sheet.getCellRange("B2:C5").getCellStyle().setNumberFormat("\"$\"#,##0");
//Add a pie chart to the worksheet
Chart chart = sheet.getCharts().add(ExcelChartType.Pie);
//Set data range for the chart
chart.setDataRange(sheet.getCellRange("B2:B5"));
chart.setSeriesDataFromRange(false);
//Set position of the chart
chart.setLeftColumn(3);
chart.setTopRow(1);
chart.setRightColumn(11);
chart.setBottomRow(20);
//Set and format chart title
chart.setChartTitle("Sales by year");
chart.getChartTitleArea().isBold(true);
chart.getChartTitleArea().setSize(12);
//Get a specified series in the chart
ChartSerie cs = chart.getSeries().get(0);
//Set category labels for the series
cs.setCategoryLabels(sheet.getCellRange("A2:A5"));
//Set values for the series
cs.setValues(sheet.getCellRange("B2:B5"));
//Show data labels for data points
cs.getDataPoints().getDefaultDataPoint().getDataLabels().hasValue(true);
//Save the result file
workbook.saveToFile("PieChart.xlsx", ExcelVersion.Version2016);
}
}
How to Create a Doughnut Chart in Excel Programmatically
Creating a doughnut chart is very similar to a pie chart, with one key difference: the chart type and the ability to set the doughnut hole size. Here’s how you can create a doughnut chart in Excel:
- Initialize a Workbook: Same as for a pie chart.
- Add Data to Worksheet: Populate cells with your data.
-
Add a Chart: Use the
Worksheet.getCharts().add()method to add a new chart, specifyingExcelChartType.Doughnut. - Set Chart Position: Define the chart's location and size.
-
Set Chart Data Range: Specify the data range and set
setSeriesDataFromRange(false). - Set Chart Title: Assign a title.
- Save the Workbook: Save the workbook to an Excel file.
import com.spire.xls.*;
import com.spire.xls.charts.ChartSerie;
import com.spire.xls.charts.ChartSeries;
import java.awt.*;
public class CreateDoughnutChart {
public static void main(String[] args) {
//Create a Workbook object
Workbook workbook = new Workbook();
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Insert data to specified cells
sheet.getCellRange("A1").setValue("Country");
sheet.getCellRange("A2").setValue("Cuba");
sheet.getCellRange("A3").setValue("Mexico");
sheet.getCellRange("A4").setValue("German");
sheet.getCellRange("A5").setValue("Japan");
sheet.getCellRange("B1").setValue("Sales");
sheet.getCellRange("B2").setNumberValue(6000);
sheet.getCellRange("B3").setNumberValue(8000);
sheet.getCellRange("B4").setNumberValue(9000);
sheet.getCellRange("B5").setNumberValue(8500);
//Set cell styles
sheet.getCellRange("A1:B1").setRowHeight(15);
sheet.getCellRange("A1:B1").getCellStyle().setColor(Color.darkGray);
sheet.getCellRange("A1:B1").getCellStyle().getExcelFont().setColor(Color.white);
sheet.getCellRange("A1:B5").getCellStyle().setVerticalAlignment(VerticalAlignType.Center);
sheet.getCellRange("A1:B5").getCellStyle().setHorizontalAlignment(HorizontalAlignType.Center);
//Set number format
sheet.getCellRange("B2:C5").getCellStyle().setNumberFormat("\"$\"#,##0");
//Add a doughnut chart to the worksheet
Chart chart = sheet.getCharts().add(ExcelChartType.Doughnut);
//Set data range for chart
chart.setDataRange(sheet.getCellRange("A1:B5"));
chart.setSeriesDataFromRange(false);
//Set position of the chart
chart.setLeftColumn(3);
chart.setTopRow(1);
chart.setRightColumn(11);
chart.setBottomRow(20);
//Set chart title
chart.setChartTitle("Market share by country");
chart.getChartTitleArea().isBold(true);
chart.getChartTitleArea().setSize(12);
//Show data labels for data points
ChartSeries series = chart.getSeries();
for (int i = 0 ; i < series.size() ; i++) {
ChartSerie cs = series.get(i);
cs.getDataPoints().getDefaultDataPoint().getDataLabels().hasPercentage(true);
}
//Set the legend position of the chart
chart.getLegend().setPosition(LegendPositionType.Top);
//Save the result file
workbook.saveToFile("DoughnutChart.xlsx", ExcelVersion.Version2016);
}
}
By following these steps, you can easily create charts with Java that are visually appealing and convey information effectively.
Conclusion
This tutorial has demonstrated the seamless process of generating both pie and doughnut charts in Excel using Spire.XLS for Java. You've learned how to set up the library, prepare data, and programmatically configure various chart properties, including data ranges, titles, and data labels. The ability to create a pie chart in Excel and create a doughnut chart in Excel programmatically offers immense value for automating reports and dynamically visualizing data. Embrace the power of Spire.XLS for Java to streamline your Excel automation tasks and unlock more advanced charting possibilities for your applications.
Top comments (0)