• 通过反射调用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引用 

  • 相关阅读:
    Selenium3+python3自动化(十六)--单选框和复选框(radiobox、checkbox)
    Selenium3+python3自动化(十五)--JS处理滚动条,window.scrollTo(xpos,ypos)
    Selenium3+python3自动化(十四)--alertsconfirmprompt
    Selenium3+python3自动化(十三)--select下拉框
    Selenium3+python3自动化(十二)--iframe
    UPC-5627 Boxes(思维)
    UPC-5007 High Score(计算)
    UPC-5003 Dunglish(模拟)
    Hrbust-1830 第一个重复出现的数(线段树区间最值查询)
    UPC-5599 Minimum Sum(线段树求区间最小值+二分区间计数)
  • 原文地址:https://www.cnblogs.com/Ricky81317/p/1373237.html
Copyright © 2020-2023  润新知