gpt4 book ai didi

c# - 使用 Word.Interop 创建嵌套字段

转载 作者:行者123 更新时间:2023-11-30 17:53:50 24 4
gpt4 key购买 nike

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

虽然提供的代码涵盖了要求,但它存在一些主要问题(如果阅读一些代码注释,您会发现),例如:

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

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

所以,我的问题是:

  • 谁能提供(替代)C# 源代码,它比我的更健壮并且允许我将嵌套字段添加到“Microsoft Word”文档?

最佳答案

我创建了一个通用实现来使用 VSTO for Microsoft Word 创建非嵌套和嵌套字段。可以在this中查看相关源码要旨。我从文章 Nested Fields in VBA 移植了 VBA 源代码到 C# 并应用了一些改进。

仍然不完美(需要一些额外的错误处理),但比使用依赖于用户界面状态的 Selection 对象的解决方案要好得多!

关于c# - 使用 Word.Interop 创建嵌套字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16774411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com