使用Word.Interop创建嵌套字段
本文关键字:嵌套 字段 创建 Interop Word 使用 | 更新日期: 2023-09-27 18:15:45
目前我正在使用VSTO,更准确地说,是使用c#和"Microsoft Word"应用程序插件。我确实希望以编程方式创建嵌套字段。我已经提出了以下源代码(用于测试目的):
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, EventArgs e)
{
// TODO This is just a test.
this.AddDocPropertyFieldWithinInsertTextField("Author", ".''''FileName.docx");
}
private void AddDocPropertyFieldWithinInsertTextField(string propertyName, string filePath)
{
// TODO Horrible, since we rely on the UI state.
this.Application.ActiveWindow.View.ShowFieldCodes = true;
Word.Selection currentSelection = this.Application.ActiveWindow.Selection;
// Add a new DocProperty field at the current selection.
currentSelection.Fields.Add(
Range: currentSelection.Range,
Type: Word.WdFieldType.wdFieldDocProperty,
Text: propertyName,
PreserveFormatting: false
);
// TODO The following fails if a DocProperty with the specified name does not exist.
// Select the previously inserted field.
// TODO This is horrible!
currentSelection.MoveLeft(
Unit: Word.WdUnits.wdWord,
Count: 1,
Extend: Word.WdMovementType.wdExtend
);
// Create a new (empty) field AROUND the DocProperty field.
// After that, the DocProperty field is nested INSIDE the empty field.
// TODO Horrible again!
currentSelection.Fields.Add(
currentSelection.Range,
Word.WdFieldType.wdFieldEmpty,
PreserveFormatting: false
);
// Insert text BEFORE the inner field.
// TODO Horror continues.
currentSelection.InsertAfter("INCLUDETEXT '"");
// Move the selection AFTER the inner field.
// TODO See above.
currentSelection.MoveRight(
Unit: Word.WdUnits.wdWord,
Count: 1,
Extend: Word.WdMovementType.wdExtend
);
// Insert text AFTER the nested field.
// TODO See above.
currentSelection.InsertAfter("''''" + filePath + "'"");
// TODO See above.
this.Application.ActiveWindow.View.ShowFieldCodes = false;
// Update the fields.
currentSelection.Fields.Update();
}
虽然提供的代码涵盖了需求,但它有一些主要的问题(正如您在阅读一些代码注释时可以看到的),例如:
- 它并不健壮,因为它依赖于应用程序的UI状态。
- 表示详细信息。在我看来,这个任务并没有那么复杂。
- 这并不容易理解(重构可能会有所帮助,但通过解决问题1。和2。
我在WWW上做了一些研究,但还没有找到一个干净的解决方案。
那么,我的问题是:
- 有人可以提供(替代)c#源代码,这是更健壮比我的,并允许我添加嵌套字段到"微软Word"文档?
我已经创建了一个通用实现,可以使用Microsoft Word的VSTO创建非嵌套字段和嵌套字段。您可以在此Gist中看到相关的源代码。我从文章《VBA中的嵌套字段》中移植了VBA源代码到c#,并进行了一些改进。
仍然不完美(需要一些额外的错误处理),但比Selection
对象的解决方案要好得多,后者依赖于用户界面的状态!