2009-10-06 99 views
6

有誰知道如何簡單地打開和關閉Excel工作簿?C#:如何打開和關閉Excel工作簿?

我不需要從文件中讀取任何數據,我只需要打開並關閉它。 (*)

我猜我需要引用Microsoft.Office.Interop.Excel程序集。


*原因:我已經配置了第三方庫(Aspose)的數據透視表信息。現在我需要讀取生成的數據透視表。

不幸的是,Aspose庫在運行時無法生成數據透視表。它需要有人來open the file with Excel,以便Excel可以生成數據透視表值。

回答

8

引用的Microsoft.Office.Interop.Excel也確保在最後清理後。

using Excel = Microsoft.Office.Interop.Excel; 

     Excel.ApplicationClass _Excel; 
     Excel.Workbook WB; 
     Excel.Worksheet WS; 

    try 
     { 

     _Excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
     WB = _Excel.Workbooks.Open("FILENAME", 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing); 

      //do something 

     } 
     catch (Exception ex) 
     { 
      WB.Close(false, Type.Missing, Type.Missing); 

      throw; 
     } 
     finally 
     { 
      GC.Collect(); 
      GC.WaitForPendingFinalizers(); 

      System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB); 

      System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel); 


     } 
+0

執行此操作時遇到錯誤沒有爲Microsoft.Office.Interop.Excel.ApplicationClass類型定義的構造函數請參閱此更正。 http://stackoverflow.com/questions/14016264/microsoft-office-interop-excel-applicationclass-has-no-constructor-defined – Desmond 2013-10-31 13:04:22

+1

我也會添加'_Excel.Quit()'來最終阻止關閉Excel應用程序。 – arthur 2015-05-11 15:58:52

相關問題