2011-05-31 199 views
4

是否可以通過Microsoft.Office.Interop.Excel.ApplicationClass確定Excel是以32位還是64位運行?

編輯
的解決方案應爲Excel 2010和Excel 2007從Excel應用程序對象中查找位(32位/ 64位)?

+0

您的意思是您的程序與Excel不在同一個進程中? – 2011-05-31 12:56:34

+1

@Simon - 我不太明白你的問題。 Excel自動進程外,所以沒有程序可以在同一個進程中與Excel交談。如果我有一個ApplicationClass對象(通過Excel互操作),我想知道是否可以確定關聯的Excel進程是運行32位還是64位(必須是Excel 2010) – SFun28 2011-05-31 13:00:30

+0

即對象模型是否支持信息關於Excel進程的位數 – SFun28 2011-05-31 13:01:46

回答

6

此代碼應該給你的Excel「位數」既工作。

Microsoft.Office.Interop.Excel.ApplicationClass app = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
if (System.Runtime.InteropServices.Marshal.SizeOf(app.HinstancePtr) == 8) 
{ 
    // excel 64-bit 
} 
else 
{ 
    // excel 32-bit 
} 

編輯:這裏是另一個應該針對以前版本的Excel工作以及版本。只需傳遞一個ApplicationClass參考:

public static ExcelVersion GetExcelVersion(object applicationClass) 
    { 
     if (applicationClass == null) 
      throw new ArgumentNullException("applicationClass"); 

     PropertyInfo property = applicationClass.GetType().GetProperty("HinstancePtr", BindingFlags.Instance | BindingFlags.Public); 
     if (property == null) 
      return ExcelVersion.Excel; 

     return (System.Runtime.InteropServices.Marshal.SizeOf(property.GetValue(applicationClass, null)) == 8) ? ExcelVersion.Excel2010_64 : ExcelVersion.Excel2010_32; 
    } 

    public enum ExcelVersion 
    { 
     Excel, // before 2010, so 32 bits 
     Excel2010_32, 
     Excel2010_64 
    } 
+0

我也想提出這個問題,但我沒有這樣做,因爲它只適用於Excel 2010. – 2011-05-31 13:18:02

+0

@丹尼爾 - 有沒有一種解決方案可以與Excel 2007一起使用。實際上,我的問題的目的是確定我是在運行64位2010還是32位2007.我有一個混合環境。 – SFun28 2011-05-31 13:22:02

+0

我想我可以嘗試獲取HinstancePtr,如果失敗,那麼我知道我正在運行32位,因爲平臺是<2010只有32位?會拋出什麼異常?我的程序集是針對14.0進行編譯的,但是當我知道2007是在框中時,我在app.config中將程序集重定向到12.0。 – SFun28 2011-05-31 13:26:58