后期绑定的Excel与.NET绑定、后期、NET、Excel

2023-09-04 23:34:23 作者:長野

我需要添加值在Word文档我的书签。在那里,我确实需要使用后期绑定来实现这一点。

我已经高达提取书签,但我要如何更改值?

 对象书签= @OfferRef;
    键入applicationType = Type.GetTypeFromProgID(Word.Application);
    反对的applicationObject = Activator.CreateInstance(applicationType);

    反对documentsObject = applicationType.InvokeMember(文档,System.Reflection.BindingFlags.GetProperty,
     空,的applicationObject,NULL);
    applicationType.InvokeMember(可见,System.Reflection.BindingFlags.SetProperty,空,的applicationObject,
     新对象[] {真});

    键入documentsType = documentsObject.GetType();
    反对documentObject = documentsType.InvokeMember(添加,BindingFlags.InvokeMethod,空,documentsObject,
     新对象[] {@E:\ offer.doc});

    键入documentType = documentObject.GetType();
    对象fieldsBookMarks = documentType.InvokeMember(书签,BindingFlags.GetProperty,空,documentObject,NULL);
    键入typeBookMarks = fieldsBookMarks.GetType();

    对象书签= typeBookMarks.InvokeMember(项目,BindingFlags.InvokeMethod,空,fieldsBookMarks,新的对象[] {书签});
    类型类型= bookMark.GetType();
    对象范围= type.InvokeMember(范围,BindingFlags.GetProperty,空,书签,NULL);
    TYPE = Range.GetType();
 

解决方案

这是您在找什么?

另外,你可能想看看动态的关键字,在C#4可用它会使你的code更容易编写和阅读。

比较code,如图4至code在图5

.NET 简单 高效 避免OOM的Excel工具

I need to add values for my "BookMarks" in a Word document. There I do need to achieve this using late binding.

I have extracted upto book mark, but how do I change the value?

    object bookMark = @"OfferRef";
    Type applicationType = Type.GetTypeFromProgID("Word.Application");
    object applicationObject = Activator.CreateInstance(applicationType);

    object documentsObject = applicationType.InvokeMember("Documents", System.Reflection.BindingFlags.GetProperty,
     null, applicationObject, null);
    applicationType.InvokeMember("Visible", System.Reflection.BindingFlags.SetProperty, null, applicationObject,
     new object[] { true });

    Type documentsType = documentsObject.GetType();
    object documentObject = documentsType.InvokeMember("Add", BindingFlags.InvokeMethod, null, documentsObject,
     new Object[] { @"e:\offer.doc"});

    Type documentType = documentObject.GetType();
    object fieldsBookMarks = documentType.InvokeMember("BookMarks", BindingFlags.GetProperty, null, documentObject, null);
    Type typeBookMarks = fieldsBookMarks.GetType();

    object bookMark = typeBookMarks.InvokeMember("Item", BindingFlags.InvokeMethod, null, fieldsBookMarks, new object[] { bookMark });
    Type type = bookMark.GetType();
    object Range = type.InvokeMember("Range", BindingFlags.GetProperty, null, bookMark, null);
    type = Range.GetType();

解决方案

Is this what you are looking for?

In addition you might want to take a look at the dynamic keyword that is available in C# 4. It will make your code easier to write and read.

Compare the code in figure 4 to the code in figure 5