尝试使用数据在XLS文件中创建Excel图表

时间:2016-06-13 18:34:46

标签: c# visual-studio office-interop excel-interop

我目前的问题是数据显示在excel文件中,但是图表没有正确显示。我正在尝试方法1:http://www.dotnetperls.com/excel。 我已经看过这个:Excel Interop Apply Chart Template

图表:(http://imgur.com/a/btgWT) 顶部图像是我得到的底部图像是我想要的。

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

1 个答案:

答案 0 :(得分:0)

发现必须在服务器上安装MS office才能使用Interop。所以,最终使用了EPPlus。它是一个使用OfficeOpenXML的很棒的库。