13 years C/C++/C# programing, focus on embedded and mobile device development.

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

因项目所需,采用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" });


 

posted on 2007-08-02 14:49  woaiusd  阅读(4503)  评论(1编辑  收藏  举报