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

时间:2017-02-23 10:57:59

标签: c# excel charts spire

这是我的代码:

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;

是错误的错误:

 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

我试图将图例键添加到我的图表中。我认为这条线可以帮助我。你知道怎么解决吗?

2 个答案:

答案 0 :(得分:1)

尝试使用以下代码设置图例键:

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

答案 1 :(得分:1)

试试这个:

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