Search code examples
c#excelchartsepplus

How to create a chart with EPPlus with multiple series?


I'm trying to create this chart using EPPlus:

Area            Imports         Exports
North America   9.00010837      14.54751448
South America   7.878137347     4.878011063
Europe          32.41924303     39.37317481
Middle East     6.859031587     12.94288951
Africa          7.611513341     2.938054884
Asia            36.23196633     25.32035526

The result should look like:

Excel Column clustered chart

Here's my code:

dataSheet.Cells["A1"].Value = "Area";
dataSheet.Cells["B1"].Value = "Imports";
dataSheet.Cells["C1"].Value = "Exports";

var row = 2;
foreach (var item in items)
{
    dataSheet.Cells["A" + row].Value = item.GeographicalAreaPersianName;
    dataSheet.Cells["B" + row].Value = item.ImportsShare;
    dataSheet.Cells["C" + row].Value = item.ExportsShare;
    row++;
}


var diagram = diagramSheet.Drawings.AddChart("chart", eChartType.ColumnClustered);

for (int i = 2; i <= row; i++)
{
    var series = diagram.Series.Add($"'Data'!B{i}:C{i}", $"'Data'!A{i}:A{i}");
}
diagram.Border.Fill.Color = System.Drawing.Color.Green;

Yet what I get is this result:

Excel Column clustered chart

As you can see series title is not shown correctly and I can't find proper help in EPPlus. How can I correct this?


Solution

  • Let us say that data are stored as demonstrated by the following screenshot:

    excel data

    The following should do the trick:

    var diagram = worksheet.Drawings.AddChart("chart", eChartType.ColumnClustered);
    
    for (int i = 2; i <= row; i++)
     {
      var series = diagram.Series.Add($"B{i}:C{i}", "B1:C1");
      series.Header = worksheet.Cells[$"A{i}"].Value.ToString();
     }
    diagram.Border.Fill.Color = System.Drawing.Color.Green;
    

    The second parameter of Add method stands for title of series {"Imports", "Exports"}

    For the Areas, you have to set the header.

    Resulting chart looks like: (Actual result of code above):

    excel column clustered chart