我编写了简单的代码来打开一个 Word 文件 (.docx) 并为该文件设置属性。这段代码完全可以自己工作。但是当 C# 打开 Microsoft Word 时,我应该更新所有字段以查看从我的代码更新的真实值!
我想知道,当 Microsoft Word 打开时,我在代码中做了什么,所有属性都具有真实值并且不再需要自己更新属性?
这是我的代码:
提示:字典属性包含属性名称和值。
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);
}
}