我正在尝试使用EPPlus自动在Excel中添加一个简单的折线图。我已经知道包含我想要使用的数据的单元格范围。我希望图表如下所示:
Before
和After
列比显示的内容要多得多。
我正在使用此代码创建图表并对其进行定位,但我不确定如何设置图表使用的数据:
ExcelChart ec = ws.Drawings.AddChart("Line Time Graph", OfficeOpenXml.Drawing.Chart.eChartType.Line);
ec.Title.Text = "Benchmarks";
ec.SetPosition(_times.Count + 2, 0, 1, 0);
它可能与ec.Series.Add
有关,但我不确定如何正确使用它。如果你能指出我正确的方向,那就太好了。
答案 0 :(得分:10)
希望这可以帮助你:
ExcelChart ec = ws.Drawings.AddChart("Line Time Graph", OfficeOpenXml.Drawing.Chart.eChartType.Line);
ec.Title.Text = "Benchmarks";
ec.SetPosition(_times.Count + 2, 0, 1, 0);
ec.SetSize(800, 600);
var ran1 = sheet.Cells["A3:A10"];
var ran2 = sheet.Cells["G3:G10"]; // label range if there is. Otherwise, let select blank range then edit XML data later to remove 'c:cat' tags (bellow example)
var serie1 = ec.Series.Add(ran1, ran2);
// use serie1 variable to format and so on
// set serie1.HeaderAddress to A2 also
var ran1 = sheet.Cells["B3:B10"];
var serie2 = ec.Series.Add(ran1, ran2);
// use serie2 variable to format and so on
我刚刚测试的另一个完整示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OfficeOpenXml;
using System.IO;
using OfficeOpenXml.Drawing.Chart;
namespace TestExcelEPPluss
{
class Program
{
static void Main(string[] args)
{
ExcelPackage package = new ExcelPackage();
var sheet = package.Workbook.Worksheets.Add("TestingGraph");
Random r = new Random();
var cell = sheet.Cells["A1"];
cell.Value = "Before";
cell = sheet.Cells["B1"];
cell.Value = "After";
for (int i = 0; i < 100; i++)
{
cell = sheet.Cells[i + 2, 1];
cell.Value = r.Next(300, 500);
cell = sheet.Cells[i + 2, 2];
cell.Value = r.Next(300, 500);
}
ExcelChart ec = (ExcelLineChart)sheet.Drawings.AddChart("chart_1", eChartType.Line);
ec.SetPosition(1, 0, 3, 0);
ec.SetSize(800, 300);
//ec.Legend.Add();
var ran1 = sheet.Cells["A2:A101"];
var ran2 = sheet.Cells["0:0"];
var serie1 = (ExcelLineChartSerie)ec.Series.Add(ran1, ran2);
serie1.Header = sheet.Cells["A1"].Value.ToString();
ran1 = sheet.Cells["B2:B101"];
var serie2 = ec.Series.Add(ran1, ran2);
serie2.Header = sheet.Cells["B1"].Value.ToString();
var xml = ec.ChartXml;
var lst = xml.GetElementsByTagName("c:lineChart");
foreach (System.Xml.XmlNode item in lst[0].ChildNodes)
{
if (item.Name.Equals("ser"))
{
foreach (System.Xml.XmlNode subitem in item.ChildNodes)
{
if (subitem.Name.Equals("c:cat"))
{
item.RemoveChild(subitem);
break;
}
}
}
}
string path = @"C:\test1.xlsx";
File.WriteAllBytes(path, package.GetAsByteArray());
package.Dispose();
Console.WriteLine("Done - Path: {0}", path);
Console.ReadLine();
}
}
}
c:cat
是ser
系列的类别,请从图表xml中删除c:cat
标记,然后您的图表将使用1,2,3,4,5,...
作为该类别的默认值(此处为x轴) )。