Creating Excel Charts in C# Using EPPlus
Excel charts provide an effective way to visualize data. In this article, we will learn how to create and customize charts in an Excel file using the EPPlus library in C#.
Understanding Excel's Chart Object
In Excel, a chart is a special type of object that can be added to a worksheet. The EPPlus library provides the ExcelChart
class that represents a chart in an Excel worksheet. This class provides a wide range of properties and methods to
work with charts.
Creating Basic Charts (Bar, Line, Pie)
Bar Chart
Let's start by creating a simple bar chart. First, we need to add data to the worksheet that we want to represent in the chart:
var package = new ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells["A1"].Value = "Category";
worksheet.Cells["B1"].Value = "Value";
worksheet.Cells["A2"].Value = "A";
worksheet.Cells["B2"].Value = 10;
worksheet.Cells["A3"].Value = "B";
worksheet.Cells["B3"].Value = 20;
var chart = worksheet.Drawings.AddChart("BarChart", eChartType.ColumnClustered);
chart.SetPosition(1, 0, 2, 0);
chart.SetSize(400, 300);
var series = chart.Series.Add(worksheet.Cells["B2:B3"], worksheet.Cells["A2:A3"]);
package.SaveAs(new FileInfo(@"C:\path\to\your\file.xlsx"));
Line Chart
Creating a line chart is quite similar to creating a bar chart. The only difference is the type of chart we specify when adding a chart to the worksheet:
var chart = worksheet.Drawings.AddChart("LineChart", eChartType.Line);
//... Rest of the code is the same as above
Pie Chart
And here's how to create a pie chart:
var chart = worksheet.Drawings.AddChart("PieChart", eChartType.Pie);
//... Rest of the code is the same as above
Formatting and Customizing Charts
EPPlus provides a variety of options to format and customize charts. Here's an example of how to customize the title and legend of the chart:
chart.Title.Text = "My Chart";
chart.Title.Font.Color = eThemeSchemeColor.Text1;
chart.Title.Font.Size = 14;
chart.Legend.Position = eLegendPosition.Right;
With EPPlus, you have the power to create and customize a wide range of Excel charts in your C# application. For more complex needs, refer to the official EPPlus documentation.