Search code examples
c#visual-studiooffice-interopexcel-interop

Trying to create an excel chart in a XLS file with data


My problem currently is that the data shows up like it's suppose to in the excel file but the chart doesn't appear correctly. I am trying Method 1: http://www.dotnetperls.com/excel. I have already looked at this: Excel Interop Apply Chart Template

Charts: (https://i.sstatic.net/gl6E8.jpg) The top image is what I get the bottom image is what I want.

    string tempPath = Path.GetTempPath();
        //C:\appdata...\LicenseCheck
    string folderPath = string.Format(@"{0}\LicenseCheck", tempPath);
      //The csv file with the XMAX license usage stats
    string secondPath = string.Format(@"{0}\{1}_Report_Stats_{2}_{3}.csv", 
        folderPath, productName, lastCheckedDate.Month, lastCheckedDate.Year);

    var application = new Application();
        var workbook = application.Workbooks.Open(secondPath);
        var worksheet = workbook.Worksheets[1] as Worksheet;
        object misValue = System.Reflection.Missing.Value;

        // Add chart.
        var charts = worksheet.ChartObjects() as ChartObjects;
        var chartObject = charts.Add(60, 10, 300, 300) as ChartObject;
        var chart = chartObject.Chart;

        // Set chart range.
        var range = worksheet.get_Range("A1", "C25");
        chart.SetSourceData(range);

        // Set chart properties.
        chart.ChartType = XlChartType.xlColumnClustered;
        chart.ChartWizard
        (
            Source: range
           // Title: "graphTitle",
           // CategoryTitle: "xAxis",
           // ValueTitle: "yAxis"
        );

        chartObject.Chart.ApplyChartTemplate(@"C:\\LicenseUsageStatsTemplate.crtx");

        // Save.
        workbook.SaveAs("Stats.xls", XlFileFormat.xlWorkbookNormal);
        workbook.Close(true, misValue, misValue);
        application.Quit();

        releaseObject(worksheet);
        releaseObject(workbook);
        releaseObject(application);

Solution

  • Found out that MS office had to be installed on the server to use Interop. So, ended up using EPPlus. It's an awesome library that uses OfficeOpenXML.