C# 使用c向word添加自定义文档属性#
我尝试使用c#工具向word添加自定义文档属性。C# 使用c向word添加自定义文档属性#,c#,properties,ms-word,C#,Properties,Ms Word,我尝试使用c#工具向word添加自定义文档属性。 我可以编辑内置属性的值,如author等 但是有了这段代码,我没有得到任何例外,但是word文档中没有自定义属性 object oDocCustomProps; string strIndex = String.Empty; string strValue; Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Appli
我可以编辑内置属性的值,如author等 但是有了这段代码,我没有得到任何例外,但是word文档中没有自定义属性
object oDocCustomProps;
string strIndex = String.Empty;
string strValue;
Microsoft.Office.Interop.Word.Application wordApp =
new Microsoft.Office.Interop.Word.Application { Visible = false };
Microsoft.Office.Interop.Word.Document doc =
wordApp.Documents.Open("C:\\test.docx", ReadOnly: false, Visible: false);
oDocCustomProps = document.CustomDocumentProperties;
Type typeDocCustomProps = oDocCustomProps.GetType();
strIndex = "Testindex";
strValue = "Testvalue";
object[] oArgs = {strIndex, false, MsoDocProperties.msoPropertyTypeString, strValue};
typeDocCustomProps.InvokeMember("Add", BindingFlags.Default | BindingFlags.InvokeMethod,
null, oDocCustomProps, oArgs);
document.save();
document.close();
编辑
你可以这样做
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application { Visible = false };
Microsoft.Office.Interop.Word.Document Doc = wordApp.Documents.Open("C:\\test.docx", ReadOnly: false, Visible: false);
Doc.BuiltInDocumentProperties["Title"].Value = this.Title.Text;
Doc.BuiltInDocumentProperties["Subject"].Value = this.Subject.Text;
Doc.BuiltInDocumentProperties["Category"].Value = this.Category.Text;
Doc.BuiltInDocumentProperties["Keywords"].Value = this.Keywords.Text;
Doc.BuiltInDocumentProperties["Author"].Value = this.Author.Text;
Doc.BuiltInDocumentProperties["Comments"].Value = this.Comments.Text;
我也有同样奇怪的事情,结果证明,如果只更改CustomDocumentProperties,word不会保存!您需要通过将doc.saved设置为false来告诉word它必须保存 希望这有帮助。 顺致敬意,
弗兰克现在你可以这样做了:
dynamic properties = null;
try
{
properties = Globals.ThisAddIn.Application.ActiveDocument.CustomDocumentProperties;
// Testing purposes:
properties.Add("SomeCustomProp", false, MsoDocProperties.msoPropertyTypeString, "SomeCustomValue");
properties.Add("SomeOtherCustomProp", false, MsoDocProperties.msoPropertyTypeString, "SomeOtherValue");
properties.Add("SomeNumericCustomProp", false, MsoDocProperties.msoPropertyTypeNumber, 1982331);
}
finally
{
Marshal.ReleaseComObject(properties);
}
以前建议释放COM对象,但我不确定是否仍然需要
而且,代替
properties = Globals.ThisAddIn.Application.ActiveDocument.CustomDocumentProperties;
只需使用您自己对应用程序的引用,然后使用.ActiveDocument.CustomDocumentProperties代码>
注意:这与问题中的编辑相同-只是使用动态而不是手动反射。我可以编辑内置属性的值,如author等。但我的问题是添加CustomDocumentProperties我的编辑对我有效。。。但我现在不知道为什么:我太爱弗兰克了!
properties = Globals.ThisAddIn.Application.ActiveDocument.CustomDocumentProperties;