如何从Excel应用程序对象中确定位数(32位/64位)?

5
能否从Microsoft.Office.Interop.Excel.ApplicationClass中确定Excel运行在32位还是64位?

编辑
解决方案应适用于Excel 2010和Excel 2007。

你的意思是你的程序不在同一个进程中与Excel吗? - Simon Mourier
1
@Simon - 我不太明白你的问题。Excel是自动化的外部进程,因此没有程序可以在同一进程中与Excel通信。如果我有一个ApplicationClass对象(通过Excel互操作),我想知道关联的Excel进程是否运行在32位或64位上(必须是Excel 2010)。 - Suraj
对象模型是否支持关于 Excel 进程的位数信息? - Suraj
你可能正在进行中,但好的,我明白了问题 :-) - Simon Mourier
2个回答

9
这段代码应该能够给你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
    }

我本想建议这个,但我还是克制了自己,因为它只适用于Excel 2010。 - Daniel Hilgarth
@Daniel - 有没有适用于Excel 2007的解决方案。实际上,我提出这个问题的目的是为了确定我是否正在运行64位的2010还是32位的2007。我有一个混合环境。 - Suraj
我想我可以尝试获取HinstancePtr,如果失败了,那么我就知道我正在运行32位,因为平台 < 2010 只有32位?会抛出什么异常?我的汇编是针对14.0编译的,但当我知道2007在框中时,我会在app.config中进行汇编重定向到12.0。 - Suraj
我的解决方案不起作用。在我尝试/捕获之前,.net会抛出MissingMethodException异常。 - Suraj

0
也许这个可以工作(用Excel 2013 ff.帮我做一下)。
try
{
    Type officeType = Type.GetTypeFromProgID("Excel.Application");
    object excelInstance = Activator.CreateInstance(officeType);
    if (excelInstance != null)
    {
        string results = officeType.InvokeMember("OperatingSystem", BindingFlags.GetProperty, null, excelInstance, null).ToString();
        if (!string.IsNullOrEmpty(results))
            detectedExcelPlatform = results.Contains("64")?EDetectExcelPlattform.Force64Bit:EDetectExcelPlattform.Force32Bit;
        officeType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, excelInstance, null);
    }
}
catch
{
    // To Ignore
}

EDetectExcelPlattform并不重要,因为它只是我的代码中的一部分。可以用bool类型的结果替换。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接