[英]Create Chart in Excel using EPPLUS in c#
我正在使用EPPLUS库并尝试绘制饼图。 打开下载的excel时,我在“图表”区域中没有任何数据或范围选择。 图表仅显示单个文本,它是图表的标题。 我的代码是:
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;
}
您对chart.Series.Add()的调用需要采用两个ExcelRange值,第一个用于值,第二个用于类别键。
这是一个对我有用的代码片段:
chart.Series.Add(ExcelRange.GetAddress(dataRowStart, dataValueColumn, dataRowEnd, dataValueColumn), ExcelRange.GetAddress(dataRowStart, dataCategoryColumn, dataRowEnd, dataCategoryColumn));
其中dataRowStart,dataValueColumn,dataRowEnd,dataCategoryColumn是所有依赖于数据源的局部整数变量。
此外,ExcelRanges不应包含标题行。
这是指向github上的EPPlus示例c#文件的链接,其中包括当前支持的图表。 https://github.com/pruiz/EPPlus/blob/master/SampleApp/Sample6.cs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.