能否从Microsoft.Office.Interop.Excel.ApplicationClass中确定Excel运行在32位还是64位?
编辑
解决方案应适用于Excel 2010和Excel 2007。
编辑
解决方案应适用于Excel 2010和Excel 2007。
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
}
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类型的结果替换。