使用 Word.Interop 创建嵌套字段

2024-02-14

目前,我正在使用 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();
    }

尽管提供的代码满足了要求,但它还有一些不足major问题(如果阅读一些代码注释,您会发现),例如:

  1. 它并不健壮,因为它依赖于应用程序的 UI 状态。
  2. 是冗长的。在我看来,任务并不那么复杂。
  3. 这并不容易理解(重构可能会有所帮助,但通过解决问题 1. 和 2.,这个缺点应该消失)。

我在 WWW 上做了一些研究,但还没有找到一个干净的解决方案。

所以,我的问题是:

  • 有人可以提供(替代)C# 源代码吗?robust比我的好,这允许我将嵌套字段添加到“Microsoft Word”文档中?

我创建了一个通用实现,可以使用 VSTO for Microsoft Word 创建非嵌套和嵌套字段。相关源码可以查看this https://gist.github.com/FlorianWolters/6257233要旨。我已经从文章中移植了VBA源代码VBA 中的嵌套字段 http://stoptyping.co.uk/word/nested-fields-in-vba到 C# 并应用了一些改进。

仍然不完美(需要一些额外的错误处理),但比带有Selection对象,它依赖于用户界面的状态!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Word.Interop 创建嵌套字段 的相关文章

随机推荐