查找位数(32位/ 64位)从Excel应用程序对象?位数、应用程序、对象、Excel

2023-09-03 15:07:00 作者:为你痴为你傻

是否有可能确定在从Microsoft.Office.Interop.Excel.ApplicationClass 32位或64位的Excel是否运行? 修改的应该为Excel 2010和Excel 2007中的解决方案

Is it possible to determine whether Excel is running in 32-bit or 64-bit from the Microsoft.Office.Interop.Excel.ApplicationClass? EditThe solution should work for both Excel 2010 and Excel 2007

推荐答案

这code应该给你的Excel的位数。

This code should give you the "bitness" of 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的previous版本以及工作版本。只是传递一个ApplicationClass参考吧:

here is another version that should work for previous versions of Excel as well. Just pass an ApplicationClass reference to it:

    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
    }