现在的位置: 首页 > 综合 > 正文

通过反射调用COM组件的一个例子

2011年01月03日 ⁄ 综合 ⁄ 共 1352字 ⁄ 字号 评论关闭

有一个朋友问如何可以版本无关的调用Office程序,以下是我的回答:

如果你是在C#项目中采用添加Com引用的方式来操作Office组件的话,版本依赖似乎是肯定的,尤其是调用那些同一个函数在不同Office版本中参数个数不同的时候。

针对问题1:

我能想到的和尝试过的方法就是不要在项目中直接引用Office Com组件,而是通过反射调用Office Com组件,这样应该可以解决版本问题。

基本步骤如下,只显示骨干代码,不完整,我是用word来把doc转换成htm,对于Office其他程序方式也是一样的:

object m_Word;
Type m_WordType;

m_WordType = Type.GetTypeFromProgID("Word.Application"false);

if (m_WordType == null)
    
throw new ApplicationException("获取Word类型失败");

try
{
    m_Word 
= Activator.CreateInstance(m_WordType);
    m_WordType.GetProperty(
"Visible").SetValue(m_Word, truenull);   //将启动的Word显示出来
}
catch (Exception err)
{
    
throw new ApplicationException("创建Word实例失败:" + err.Message);
}

object documents, document;
documents 
= m_WordType.GetProperty("Documents").GetValue(m_Word, null);
document 
= documents.GetType().InvokeMember("Open", BindingFlags.InvokeMethod, null, documents, new object[] { fileName });  //注意这里通过object[]传递方法的参数

document.GetType().InvokeMember(
"SaveAs", BindingFlags.InvokeMethod, null, document, new object[] { newFileName, 8 });  //有一些office常量,需要查询office的帮助找到它的具体数值,比如这里的8代表htm格式
document.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, document, new object[] { });  //关闭当前打开的文档

m_WordType.InvokeMember(
"Quit", BindingFlags.InvokeMethod, null, m_Word, new object[] { });    //退出Word程序

System.Runtime.InteropServices.Marshal.ReleaseComObject(m_Word);    //释放Com引用 

抱歉!评论已关闭.