在系列图表上设置值(Interop Excel)

时间:2017-03-16 16:10:18

标签: c# excel-interop

我使用互操作Excel在Excel文件中创建图表。

当我第一次创建图表并在系列上设置值时,我没有任何问题。

当我第二次这样做时,我有一个错误。

我创建了一个POC来重现问题:

using System;
using System.Linq;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

namespace POC_Excel
{
    static class Program
    {
        static void Main(string[] args)
        {
            Excel.Application excel = null;
            try
            {
                excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Please run Excel");
                Console.ReadLine();
                Environment.Exit(0);
            }

            try
            {
                LockUnlock(excel, true);

                var shapes = excel.ActiveSheet.Shapes;
                Console.WriteLine(" --- Create chart --- ");
                Excel.Shape shape = shapes.AddChart2(-1, Excel.XlChartType.xlColumnClustered);

                Console.WriteLine(" --- 1st chart filling --- ");
                CreateSeries(shape);

                Console.WriteLine(" --- 2nde chart filling --- ");
                CreateSeries(shape);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : " + ex);
            }
            finally
            {
                LockUnlock(excel, false);
                Console.ReadLine();
            }
        }

        static void CreateSeries(Excel.Shape shape)
        {
            var seriesCollection = (Excel.SeriesCollection)shape.Chart.SeriesCollection();
            while (0 < seriesCollection.Count)
                seriesCollection.Item(1).Delete();

            var donnee1 = new object[] { 10, 20, 30 };
            var series = seriesCollection.NewSeries();
            Console.WriteLine("Add values to serie : " + donnee1.Select(v => v.ToString()).Aggregate((a, b) => a + ", " + b));
            series.Values = donnee1;
            Console.WriteLine("Serie data : " + series.Formula);

            series.ChartType = Excel.XlChartType.xlDoughnut;

            for (int i = 0; i < donnee1.Length; i++)
            {
                Excel.Point pt = series.Points(i + 1);
                Console.WriteLine("points : " + pt.Name);
            }
        }

        private static void LockUnlock(Excel.Application excel, bool isFiger)
        {
            excel.DisplayAlerts = !isFiger;
            excel.ScreenUpdating = !isFiger;
            excel.EnableEvents = !isFiger;
            excel.Interactive = !isFiger;
        }
    }
}

你能帮帮我吗?

由于

1 个答案:

答案 0 :(得分:0)

我从未见过在一个形状上创建2个图表的能力。我怀疑那是失败的。试试这个......

$lastCharacter = substr($exampleString,-1);