【问题标题】:Find bitness (32-bit/64-bit) from Excel Application object?从 Excel 应用程序对象中查找位数(32 位/64 位)?
【发布时间】:2011-09-05 11:09:49
【问题描述】:

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

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

【问题讨论】:

  • 你的意思是你的程序和Excel不在同一个进程吗?
  • @Simon - 我不太明白你的问题。 Excel 是自动进程外的,因此没有程序可以在同一进程中与 Excel 对话。如果我有一个 ApplicationClass 对象(通过 Excel 互操作),我想知道是否可以确定关联的 Excel 进程是运行 32 位还是 64 位(必须是 Excel 2010)
  • 即对象模型是否支持有关Excel进程位数的信息
  • 我想你可能正在处理中,但是好的,我得到了问题 :-)

标签: .net excel 32bit-64bit excel-interop


【解决方案1】:

这段代码应该为您提供 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 - 是否有适用于 Excel 2007 的解决方案。其实我这个问题的目的是要判断我运行的是64位2010还是32位2007。我是混合环境。
  • 我想我可以尝试获取 HinstancePtr,如果失败了,那么我知道我正在运行 32 位,因为平台
  • 我提出的解决方案不起作用。 .net 在我有机会尝试/捕获之前抛出 MissingMethodException。
【解决方案2】:

也许这可以工作(用 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 结果替换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2019-03-07
    相关资源
    最近更新 更多