zoukankan      html  css  js  c++  java
  • 利用C#在Word自动化中操作OLE控件

    因项目所需,采用WORD模板作为报表系统的一部分,需要使用C#操作WORD文档,大部分的操作都是填充表格,难度也不是很大。但是有一份报表很特殊,WORD里面需要包含ComboBox、CheckBox控件,如下所示:


    这里关键的技术难题是找到OLE控件,然后设置其某个属性值,GOOGLE了半天,终于找到如下的代码:

    private static object FindControl(string name, Word._Document document)
            
    {
                
    try
                
    {
                    
    foreach (Word.InlineShape shape in document.InlineShapes)
                    
    {
                        
    if (shape.Type ==Word.WdInlineShapeType.wdInlineShapeOLEControlObject)
                        
    {
                            
    object oleControl = shape.OLEFormat.Object;
                            Type oleControlType 
    = oleControl.GetType();
                            
    string oleControlName = (string)oleControlType.InvokeMember("Name",
                                System.Reflection.BindingFlags.GetProperty,
    null, oleControl, null);
                            
    if (String.Compare(oleControlName, name, true,System.Globalization.CultureInfo.InvariantCulture) == 0)
                            
    {
                                
    return oleControl;
                            }

                        }

                    }


                    
    foreach (Word.Shape shape in document.Shapes)
                    
    {
                        
    if (shape.Type ==Microsoft.Office.Core.MsoShapeType.msoOLEControlObject)
                        
    {
                            
    object oleControl = shape.OLEFormat.Object;
                            Type oleControlType 
    = oleControl.GetType();
                            
    string oleControlName = (string)oleControlType.InvokeMember("Name",
                                System.Reflection.BindingFlags.GetProperty,
    null, oleControl, null);
                            
    if (String.Compare(oleControlName, name, true,System.Globalization.CultureInfo.InvariantCulture) == 0)
                            
    {
                                
    return oleControl;
                            }

                        }

                    }

                }

                
    catch
                
    {
                    
    // Returns null if the control is not found.
                }

                
    return null;
            }

    找到OLE控件后,经过尝试,发现设置其属性时,应该如下调用:

    oleControlType.InvokeMember("Value", System.Reflection.BindingFlags.SetProperty, null, oleControl, new object[] "True" });


     

  • 相关阅读:
    asp.net六大对象
    python学习之类和实例的属性;装饰器@property
    第一次写博客,不知道写什么,就随便写一点咯
    Bash脚本编写初体验
    python学习之参数传递
    2016.9.30词法分析程序 108
    实验三 108
    10.28实验二 108
    词法分析实验报告 108
    组合数据类型练习,综合练习 108
  • 原文地址:https://www.cnblogs.com/swnuwangyun/p/840298.html
Copyright © 2011-2022 走看看