我正在尝试创建一个EPPlus图表。我遇到系列标题的问题。即使使用ExcelChartSerie.HeaderAddress,它似乎也没有效果。
每个系列都使用以下代码进行初始化
ExcelBarChartSerie serie = (OfficeOpenXml.Drawing.Chart.ExcelBarChartSerie)
chartClustered.Series.Add(ExcelRange.GetAddress(fromRow, fromCol, toRow, toCol),
ExcelRange.GetAddress(fromRow, fromColH, toRow, fromColH));
ExcelAddressBase headerAddr = new ExcelAddressBase(headRow, headCol, headRow, headCol);
serie.HeaderAddress = headerAddr;
serie.Header = (string)ws.Cells[headRow, headCol].Value;
一切都很好但是我在使用图表的其余部分正确更新标题时遇到了问题。 serie.Header变量控制图例,这就是我遇到问题的地方。我知道这是一个尴尬的具体问题,但也许有人可以提供一些见解。这里有一些图片可以准确地显示我遇到问题的地方。
更改前的初始图(正确):
标签数据更改后的绘图(不正确):
答案 0 :(得分:1)
问题是您在设置HeaderAddress
时是否正在创建未附加到工作表的新Excel地址。它是一个非常微妙但重要的区别,因为Excel在查找标题值时不会知道地址实际与哪个表相关联(它不会假设图表所在的那个)。看看这个:
[TestMethod]
public void ExcelChartSerie_Header()
{
//http://stackoverflow.com/questions/27866521/epplus-excelchartserie-header-loads-once-but-doesnt-update-when-cell-is-change
var existingFile = new FileInfo(@"c:\temp\temp.xlsx");
if (existingFile.Exists)
existingFile.Delete();
using (var package = new ExcelPackage(existingFile))
{
var workbook = package.Workbook;
var ws = workbook.Worksheets.Add("newsheet");
//Some data
ws.Cells["A1"].Value = "Stuff";
ws.Cells["A2"].Value = "bar1";ws.Cells["A3"].Value = "bar2";ws.Cells["A4"].Value = "bar3";ws.Cells["A5"].Value = "bar4";ws.Cells["A6"].Value = "bar5";
ws.Cells["C1"].Value = "Canadian";
ws.Cells["C2"].Value = 53;ws.Cells["C3"].Value = 36;ws.Cells["C4"].Value = 43;ws.Cells["C5"].Value = 86;ws.Cells["C6"].Value = 86;
ws.Cells["D1"].Value = "Saudi Arabia";
ws.Cells["D2"].Value = 53;ws.Cells["D3"].Value = 36;ws.Cells["D4"].Value = 43;ws.Cells["D5"].Value = 86;ws.Cells["D6"].Value = 86;
ws.Cells["E1"].Value = "Alaskan";
ws.Cells["E2"].Value = 53; ws.Cells["E3"].Value = 36; ws.Cells["E4"].Value = 43; ws.Cells["E5"].Value = 86; ws.Cells["E6"].Value = 86;
ws.Cells["F1"].Value = "Indian";
ws.Cells["F2"].Value = 53; ws.Cells["F3"].Value = 36; ws.Cells["F4"].Value = 43; ws.Cells["F5"].Value = 86; ws.Cells["F6"].Value = 86;
//Create the chart
var chart = (ExcelBarChart)ws.Drawings.AddChart("Chart1", eChartType.ColumnClustered);
chart.SetSize(400, 300);
chart.SetPosition(10, 400);
//Apply header
for (var i = 0; i < 4; i++)
{
var serie = (ExcelBarChartSerie) chart.Series.Add(
ExcelCellBase.GetAddress(2, i + 3, 6, i + 3),
ExcelCellBase.GetAddress(2, 1, 6, 1)
);
//var headerAddr = new ExcelAddressBase("C1"); //THIS IS NOT ASSOCIATED WITH WORKSHET 'ws'
var headerAddr = ws.Cells[1, i + 3]; //THIS IS
serie.HeaderAddress = headerAddr;
//serie.Header = (string) ws.Cells[1, i + 3].Value;
}
package.Save();
}
}