C#Spire.Xls – 数据表错误(添加图例键)

这是我的代码:

using System.Drawing; using Spire.Xls; using System; using System.Windows.Forms.DataVisualization; using Spire.Xls.Charts; namespace XLS_Program { class Program { static void Main(string[] args) { Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\Users\my_user\Desktop\export222.xls"); Worksheet sheet = workbook.Worksheets["Chart1"]; /* there was some code here, not important */ chart = sheet.Charts.Add(ExcelChartType.ColumnClustered); chart.DataRange = sheet.Range[range_s]; chart.SeriesDataFromRange = true; chart.HasDataTable = true; chart.DataTable.ShowSeriesKeys = true; chart.PrimaryValueAxis.TitleArea.TextRotationAngle = 90; chart.Legend.Position = LegendPositionType.Right; workbook.SaveToFile("Excel_Charts.xlsx",ExcelVersion.Version2010); System.Diagnostics.Process.Start("Excel_Charts.xlsx"); } } } 

它工作正常。 但有一个例外。 这一行:

  chart.DataTable.ShowSeriesKeys = true; 

是cousing错误:

  System.InvalidCastException: Unable to cast object of type 'Spire.Xls.Core.Spreadsheet.Charts.ChartDataTableXls' to type 'Spire.Xls.Charts.ChartDataTable'. at Spire.Xls.Chart.get_DataTable() at XLSTest.Program.Main(String[] args) in c:\Users\my_user\Documents\SharpDevelop Projects\projekt1\projekt1\Program.cs:line 81 

我正在尝试将图例按键添加到我的图表中。 我认为这条线可以帮助我。 你知道如何解决它?

尝试这个:

 (chart as Spire.Xls.Core.Spreadsheet.Shapes.XlsChartShape).DataTable.ShowSeriesKeys = true; 

尝试下面的代码来设置图例键:

 foreach (ChartSerie cs in chart.Series) { cs.DataPoints.DefaultDataPoint.DataLabels.HasLegendKey = true; }