Reputation: 129
I am using EPPLUS library and tried to draw Pie chart. when opening downloaded excel i am not getting any data or range selection in Chart area. Chart showing only single text which is title of the chart. My code is:
public static string RunSample5(DirectoryInfo outputDir)
{
FileInfo newFile = new FileInfo(outputDir.FullName + @"\sample5.xlsx");
if (newFile.Exists)
{
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo(outputDir.FullName + @"\sample5.xlsx");
}
using (ExcelPackage package = new ExcelPackage(newFile))
{
//Open worksheet 1
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
worksheet.InsertRow(5, 2);
//Add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Product";
worksheet.Cells[1, 3].Value = "Quantity";
worksheet.Cells[1, 4].Value = "Price";
worksheet.Cells[1, 5].Value = "Value";
//Add some items...
worksheet.Cells["A2"].Value = 12001;
worksheet.Cells["B2"].Value = "Nails";
worksheet.Cells["C2"].Value = 37;
worksheet.Cells["D2"].Value = 3.99;
worksheet.Cells["A3"].Value = 12002;
worksheet.Cells["B3"].Value = "Hammer";
worksheet.Cells["C3"].Value = 5;
worksheet.Cells["D3"].Value = 12.10;
var chart = (worksheet.Drawings.AddChart("PieChart", eChartType.Pie3D) as ExcelPieChart);
chart.Title.Text = "Total";
//From row 1 colum 5 with five pixels offset
chart.SetPosition(0, 0, 5, 5);
chart.SetSize(600, 300);
ExcelAddress valueAddress = new ExcelAddress(2, 3, 6, 3);
var ser = (chart.Series.Add(valueAddress.Address, "B2:B3") as ExcelPieChartSerie);
chart.DataLabel.ShowCategory = true;
chart.DataLabel.ShowPercent = true;
chart.Legend.Border.LineStyle = eLineStyle.Solid;
chart.Legend.Border.Fill.Style = eFillStyle.SolidFill;
chart.Legend.Border.Fill.Color = Color.DarkBlue;
worksheet.View.PageLayoutView = false;
package.Save();
}
return newFile.FullName;
}
Upvotes: 1
Views: 4066
Reputation: 101
Your call to chart.Series.Add() needs to take two ExcelRange values, the first for the values, the second for the category keys.
Here's an snippet that works for me:
chart.Series.Add(ExcelRange.GetAddress(dataRowStart, dataValueColumn, dataRowEnd, dataValueColumn), ExcelRange.GetAddress(dataRowStart, dataCategoryColumn, dataRowEnd, dataCategoryColumn));
Where dataRowStart, dataValueColumn, dataRowEnd, dataCategoryColumn are all local integer variables that are dependent on the data source.
Additionally, the ExcelRanges should not include the header rows.
Here is a link to an EPPlus example c# file on github that includes presently supported charts. https://github.com/pruiz/EPPlus/blob/master/SampleApp/Sample6.cs
Upvotes: 1