Late binding Excel with .NET

2019-06-10 10:22发布

问题:

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();

回答1:

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