2017-03-16 88 views
0

我使用interop Excel在Excel文件中創建圖表。設置系列圖表(Interop 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; 
     } 
    } 
} 

你能幫助我嗎?

謝謝

+0

「這是我第二次做這件事時,我有一個錯誤。」什麼錯誤? COM異常? C#異常?它實際上打破了哪一行代碼? – Drakestar

回答

0

我從來沒有見過在一個形狀上創建2個圖表的能力。我懷疑那是失敗的。試試這個...

  Excel.Shape shape; 

      shape = shapes.AddChart2(-1, Excel.XlChartType.xlColumnClustered); 
      Console.WriteLine(" --- 1st chart filling --- "); 
      CreateSeries(shape); 

      shape = shapes.AddChart2(-1, Excel.XlChartType.xlColumnClustered); 
      Console.WriteLine(" --- 2nde chart filling --- "); 
      CreateSeries(shape); 
+0

我在POC中這樣做來重新引入問題。 它對應於2個不同的更新與我的軟件中的不同數據。 – Maverick