0

我正在使用 Office 的 Word 互操作构建一个 Word 文档。我正在通过代码设置标题样式。内容的样式正确,但是,打开创建的 word 文档时,没有为标题中的选择选择样式。这导致目录找不到标题。

object oMissing = Missing.Value;

//Start Word and create a new document.
var application = new Application();
application.Visible = true;
var document = application.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

foreach (var member in assembly.Members)
{
    //Insert a paragraph at the beginning of the document
    var paragraph = document.Content.Paragraphs.Add(ref oMissing);
    paragraph.set_Style(WdBuiltinStyle.wdStyleHeading1);
    paragraph.Range.Text = member.MemberName;
    paragraph.Range.InsertParagraphAfter();
}

document.TablesOfContents.Add(document.Content, true /*use heading styles*/, oMissing, oMissing, oMissing,
                                                    oMissing, oMissing, oMissing, oMissing, oMissing,
                                                    oMissing, oMissing);

document.SaveAs(@"C:\test.docx", oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
document.Close();
application.Quit();

此示例导致目录显示“未找到条目”。

请注意,内容的样式与标题样式正确。但是,当我手动打开文档并选择“标题 1”时,目录会正确找到条目。

任何想法为什么会发生这种情况?我是带有内置样式名称的 callign set_Style。为什么它应用样式但实际上并未被视为样式(在本例中为标题)?

更新

添加以下代码似乎只使第一个标题被识别为 Word 中的标题。

    foreach (var member in assembly.Members)
    {
        document.ActiveWindow.Selection.set_Style(WdBuiltinStyle.wdStyleHeading1);
        //Insert a paragraph at the beginning of the document
        var paragraph = document.Content.Paragraphs.Add(ref oMissing);
        paragraph.set_Style(WdBuiltinStyle.wdStyleHeading1);
        paragraph.Range.Text = member.MemberName;
        paragraph.Range.InsertParagraphAfter();
    }
4

3 回答 3

1

I have noticed difference in the order of the operations

Follow code will not generate real header, it is only looks like header

/*1*/ paragraph.set_Style(WdBuiltinStyle.wdStyleHeading1);
/*2*/ paragraph.Range.Text = "Head";
/*3*/ paragraph.Range.InsertParagraphAfter();

To solve propblem you should use this code

/*1*/ paragraph.Range.Text = "Head";
/*2*/ paragraph.set_Style(WdBuiltinStyle.wdStyleHeading1);
/*3*/ paragraph.Range.InsertParagraphAfter();
于 2014-10-31T10:28:52.027 回答
0

After Adding the Paragraph select the paragraph it might work .

paragraph.Range().Select()
于 2013-04-08T09:54:00.300 回答
0

我不得不做类似的事情,但段落没有得到风格......

然后我使用了 TypeText,然后开始工作......我也使用了 Word.Selection。我正在合并文档,但我想您的代码应该是这样的:

(行后: var document = application.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing))。我在 usings 上使用 Word = Microsoft.Office.Interop.Word,因此“Word”在选择与此相关之前。

Word.Selection selection = application.Selection;

foreach (var member in assembly.Members)
{
  selection.TypeText(member.MerberName);
  selection.set_Style(WdBuiltinStyle.wdStyleHeading1);
  selection.TypeParagraph();
}

这在这里奏效了,TOC 正在被填满。

于 2013-07-16T00:24:27.973 回答