在C#中设置Word属性的问题?

时间:2010-01-09 07:48:56

标签: c# .net ms-word office-interop

我编写了简单的代码来打开Word文件(.docx)并设置该文件的属性。这段代码完全是自己的工作。但是当C#打开Microsoft Word时,我应该更新所有字段以查看从我的代码更新的实际值!

我想知道,在我的代码中我做了什么,当Microsoft Word打开时,所有属性都有真正的值,不再需要使用mysself更新属性?

这是我的代码:

提示:字典属性包含属性名称和值。

public void SetWordFile(string FilePath, Dictionary<string, object> properties)

    {
        Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word._Document oDoc;
        object originalFormat = Missing.Value;
        object routeDocument = Missing.Value;
        object oMissing = Missing.Value;
        object saveChanges = false;
        object oDocBuiltInProps;
        object oDocAuthorProp;
        Type typeDocAuthorProp;

        oWord.Visible = true;

        object oFalse = false;
        object filePath = FilePath;

        oDoc = oWord.Documents.Open(ref filePath, ref oMissing, ref oFalse, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

        oDocBuiltInProps = oDoc.CustomDocumentProperties;
        Type typeDocBuiltInProps = oDocBuiltInProps.GetType();
        foreach (string item in properties.Keys)
        {
            oDocAuthorProp = typeDocBuiltInProps.InvokeMember("Item",
                                    BindingFlags.Default |
                                    BindingFlags.GetProperty,
                                    null, oDocBuiltInProps,
                                    new object[] { item });
            typeDocAuthorProp = oDocAuthorProp.GetType();

            typeDocAuthorProp.InvokeMember("Item",
                                       BindingFlags.Default |
                                       BindingFlags.SetProperty,
                                       null, oDocBuiltInProps,
                                       new object[] { item, properties[item] });
            Thread.Sleep(10);
        }
}

1 个答案:

答案 0 :(得分:1)

很长一段时间后......

我发现了我真正的大问题。(意思是我的同事找到了这个解决方案)

在foreach之后,我们应该使用此代码来更新所有属性

for(int i=1;i<=Counter;i++)
  oDoc.Fields[i].Update();

特别感谢我的同事