Before following the steps to create an Excel chart, let's discuss the details of the library EPPLUS that I have used to implement the Excel charts.
About EPPLUS
EPPLUS is a very helpful open-source 3rd party dll for exporting data to Excel.
EPPLUS Installation
EPPLUS library can be installed by using the NuGet Package Manager. Just right-click on your project where you want to implement this Excel Chart logic, select "Manage NuGet Packages" and search for EPPLUS and install it.
C# code to create Excel charts using EPPLUS
- ExcelPackage package = new ExcelPackage(); //To create excel package
- package.Workbook.Worksheets.Add("xyz"); //To add new sheet to Excel package with name‘ xyz’
- ExcelWorksheet testWorksheet = package.Workbook.Worksheets["xyz"]; //to get excel worksheet object by name
- ExcelChart chart = testWorksheet.Drawings.AddChart("chart", eChartType.ColumnClustered); //To add chart to added sheet of type column clustered chart
Now, in my case, I have my own list which has columns named as Month, Current Year Consumption, and Previous Year Consumption data details.These column names are important for mapping data in Excel Charts that I will explain in the next steps.
In the previous step, we have added a chart to an Excel sheet. In this case chart has a X-axis for month value and Y- axis is showing a consumption/usage for the respective month.
Now, let’s use the chart object named ’chart’ we created above to set further chart properties.
- chart.XAxis.Title.Text = "Months"; //give label to x-axis of chart
- chart.XAxis.Title.Font.Size = 10;
- chart.YAxis.Title.Text = "Usage(kwh)"; //give label to Y-axis of chart
- chart.YAxis.Title.Font.Size = 10;
- chart.SetSize(1200, 300);
- chart.SetPosition(1, 0, 5, 0);
- consumptionWorksheet.Cells[1, 1].LoadFromCollection(consumptionComparisonDetails, false, OfficeOpenXml.Table.TableStyles.Medium1);
The function LoadFromCollection is used to load data from your list to an Excel. If you noticed one thing, I am using cell[1,1] that means whenever my data table will get created using LoadFromCollection function inside my Excel sheet, it starts loading data from row 1 and column 1.Also, in this statement, I have used the second parameter value as false, this parameter is used to decide if you also want to display headers to the data table mentioned in your list. If I set it true, it will display a table with headers that have names of the columns we get in our list. However, I am manually giving header names so i set to the false as mentioned below.


Join the conversation! Your thoughts help the community grow.