如何通过 Interop (C#) 向 Word 文档添加结构化内容?

How do I add structured content to a Word Document via Interop (C#)?

感谢观看。我正在编写一些 C# 来创建基于数据集的 word 文档。使用 Microsoft.Office.Interop.Word 我可以创建一个文档,其中包含 格式 标题的部分,但没有关联的结构。换句话说,我无法在导航窗格中看到我的部分或生成 Table 的内容。

这是我正在尝试的:

Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document document = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);

document.Range(0, 0);

foreach (var solutionModel in solutions)
{
    var hText = document.Paragraphs.Add();
    hText.Format.SpaceAfter = 10f;
    hText.set_Style(Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleHeading1);
    hText.Range.Text = solutionModel.Name;
    hText.Range.InsertParagraphAfter();

    var pText = document.Paragraphs.Add();
    pText.Format.SpaceAfter = 50f;
    pText.set_Style(Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleNormal);
    pText.Range.Text = "Lorem ipsum dolor sit amet.";
    pText.Range.InsertParagraphAfter();
}

WordApp.Visible = true;

这在 Word 中呈现得很好,标题 (hText) 采用原生 Header 1 样式,但没有关联的结构。

您可以将 OutlineLevel(位于段落范围的 ParagrapFormat 上)设置为所需级别 (VBA):

ActiveDocument.Paragraphs(1).Range.ParagraphFormat.OutlineLevel = wdOutlineLevel1

您的情况 (C#):

hText.Range.Text = solutionModel.Name;
hText.Range.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevel1;

这会将所选段落添加到导航视图

最初我的想法与评论中提到的@Dirk 相同,但对其进行了测试,正如您自己所见,它在您的代码中不起作用。

经过更多研究后,我发现我的其他答案实际上并没有将正确的页眉样式应用于您添加的段落。所以我的测试结果如下:

您需要在应用样式之前设置文本

var hText = document.Paragraphs.Add();

hText.Range.Text = solutionModel.Name; // <--

hText.set_Style(Microsoft.Office.Interop.Word.WdBuiltinStyle.wdStyleHeading1);
hText.Format.SpaceAfter = 10f;
hText.Range.InsertParagraphAfter();

我添加了两个空行以引起对文本行位置的注意,但您可以将其省略。