2014-03-05 151 views
3

我已經編寫了以下簡單的C#控制檯應用程序,以從Excel工作簿中導出所有圖表。它工作得很好除非圖表自從打開文檔以來沒有被滾動到,在這種情況下會生成一個空的圖像文件。將Excel圖表導出爲圖像

using Excel = Microsoft.Office.Interop.Excel; 
using System; 
using System.Diagnostics; 

namespace ExcelExporter 
{ 
    class ChartExporter 
    { 
     const string EXPORT_TO_DIRECTORY = @"C:\Users\Sandy\Desktop\Excel\Charts"; 

     static void Main(string[] args) 
     { 
      Excel.Application app = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application") as Microsoft.Office.Interop.Excel.Application; 

      ConsoleColor c = Console.ForegroundColor; 
      Console.ForegroundColor = ConsoleColor.Green; 
      Console.Write("Export To: "); 
      Console.ForegroundColor = c; 
      string exportPath = Console.ReadLine(); 

      if (exportPath == "") 
       exportPath = EXPORT_TO_DIRECTORY; 

      Excel.Workbook wb = app.ActiveWorkbook; 

      foreach (Excel.Worksheet ws in wb.Worksheets) 
      { 
       Excel.ChartObjects chartObjects = (Excel.ChartObjects)(ws.ChartObjects(Type.Missing)); 

       foreach (Excel.ChartObject co in chartObjects) 
       { 
        Excel.Chart chart = (Excel.Chart)co.Chart; 
//     app.Goto(co, true); 
        chart.Export(exportPath + @"\" + chart.Name + ".png", "PNG", false); 
       } 
      } 

      Process.Start(exportPath); 
     } 
    } 
} 

我做了幾次失敗的嘗試滾動到對象;例如,對程序底部的註釋行(app.Goto(co, true);)僅適用於範圍。 有什麼辦法可以滾動到ChartObject,否則確保它們正確導出到圖像?

要進行測試,請使用帶有1000多行圖表的工作簿(遠遠不能超出文檔打開時的視野);在運行程序之前關閉並重新打開文檔(一旦滾動到,圖表將已經被渲染並存儲在內存中)。

+0

你可以嘗試在出口前的Excel實例可見性設置爲true以下工作。 –

+0

@TimWilliams ['_Application.Visible'](http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._application.visible.aspx)?我會試試看。 –

+0

@TimWilliams no dice = \同樣的問題。 –

回答

5

VBA,但同樣的想法可能會爲C#工作...

Dim co As ChartObject, sht As Worksheet, x As Long 
x = 1 
Set sht = ThisWorkbook.Sheets("Sheet1") 
For Each co In sht.ChartObjects 
    Application.Goto co.TopLeftCell, True 
    co.Chart.Export "C:\_stuff\test\chart" & x & ".jpg", "JPG", False 
    x = x + 1 
Next co 
+0

工作奇蹟(太快了!)。對於任何尋找C#等價物的人(因爲它適合上面的代碼):'app.Goto(co.TopLeftCell,true);' –

4

我發現我

  foreach (Excel.ChartObject co in chartObjects) 
      { 
       co.Select(); 
       Excel.Chart chart = (Excel.Chart)co.Chart; 
       chart.Export(exportPath + @"\" + chart.Name + ".png", "PNG", false); 
      }