zoukankan      html  css  js  c++  java
  • 通过反射调用COM组件的一个例子

    有一个朋友问如何可以版本无关的调用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引用 

  • 相关阅读:
    岳麓山岳麓书院
    花洲书院
    《诫子书》诸葛亮
    AI ML DL
    台湾大学林轩田机器学习基石
    LeNet
    VGGNet
    AlexNet 2012
    AS 中 Plugin for Gradle 和 Gradle 之间的版本对应关系
    AndroidStudio、gradle、buildToolsVersion关系
  • 原文地址:https://www.cnblogs.com/Ricky81317/p/1373237.html
Copyright © 2011-2022 走看看