覆盖字段内容

Overwrite field content

我正在使用此代码通过 Word Interop 将内容放入 Field

var wordApp = new Microsoft.Office.Interop.Word.Application();
var wordDoc = wordApp.Documents.Add(Path.GetFullPath("myTemplate.dotx"));
Field f = wordDoc.Fields[0];
f.Select();
wordApp.Selection.TypeText("some text");

但这只有效一次。如果我再次 运行 f.Select() 语句,我会得到一个 COMException 告诉我对象不见了。

有没有办法覆盖字段内容?或者我是否必须只能写一次 Field

当您 select 字段,然后使用 TypeText 时,会用您输入的文本替换整个字段。相反,您应该使用 Field.Result 属性:

f.Result.Text = "some text";

因此,您的代码应如下所示:

var wordApp = new Microsoft.Office.Interop.Word.Application();
var wordDoc = wordApp.Documents.Add(Path.GetFullPath("myTemplate.dotx"));
wordDoc.Fields[1].Result.Text = "some text"; // AFAIK, `Fields` collection is one-based.

// Do whatever other modifications you want, then save and close the document.

希望对您有所帮助:)