Search code examples
c#excelchartsspire

C# Spire.Xls - error with data table (adding legend keys)


This is my code:

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");

    }

}

}

And it works fine. But with one exception. This line:

 chart.DataTable.ShowSeriesKeys = true;

is cousing error:

 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

I'm trying to add legend keys to my chart. I thought this line could help me. Do you know how to fix it?


Solution

  • Try this:

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