在C#中将Word预定义样式应用于文本

Ant*_*Lev 9 c# ms-word visual-studio office365

我想将预定义的样式应用于我的段落(如Heading2),以便我可以更新我的内容表并自动填充它.

这是我的代码:

using Word = Microsoft.Office.Interop.Word;

object oMissing = System.Reflection.Missing.Value;
Word.Application oWord = new Word.Application();
Word.Document oDoc = oWord.Documents.Add(@"local path to a template", 
  ref oMissing, ref oMissing, ref oMissing);

object obrangePara = oDoc.Bookmarks[oEndOfDoc].Range;
var objpara = oDoc.Content.Paragraphs.Add(ref objrangePara);
objpara.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);
objpara.Range.Text = "some text";
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这会直观地应用样式,但在更新时它不会出现在内容列表中.当我在Word中选择文本时,它表示它具有正常的文本样式,即使它在视觉上具有Heading2样式.

如何确保正确应用预定义样式?

在这里您可以看到样式在视觉上正常,但Word将其检测为普通文本: 在此输入图像描述 在此输入图像描述

完整的代码清单:

        object oMissing = System.Reflection.Missing.Value;
        object oEndOfDoc = "\\endofdoc"; // endofdoc is a predefined bookmark
        var oTemplate = @"C:\TestLab\SantiagoReport.dotx";

        Word.Application oWord;
        Word.Document oDoc;
        oWord = new Word.Application();
        oWord.Visible = true;

        if(File.Exists(oTemplate))
        {
            oDoc = oWord.Documents.Add(oTemplate, ref oMissing, ref oMissing, ref oMissing);

            Word.Table dateTable = findTable(oDoc, "Tests Date");
            dateTable.Cell(2, 1).Range.Text = DateTime.Now.ToString();

            Word.Table snTable = findTable(oDoc, "Serial Number");
            snTable.Cell(2, 1).Range.Text = SerialNumber;

            Word.Table userTable = findTable(oDoc, "User");
            userTable.Cell(2, 1).Range.Text = User;

            Word.Table timeTable = findTable(oDoc, "Total Elapsed Time");
            timeTable.Cell(2, 1).Range.Text = String.Format("{0}h{1}m{2}s", StopWatch.Elapsed.Hours, StopWatch.Elapsed.Minutes, StopWatch.Elapsed.Seconds);

            Word.Table summaryTable = findTable(oDoc, "Summary");
            summaryTable.Cell(2, 2).Range.Text = nbLoadedTests.ToString();
            summaryTable.Cell(3, 2).Range.Text = nbSelectedTests.ToString();
            summaryTable.Cell(4, 2).Range.Text = nbPassedTests.ToString();
            summaryTable.Cell(5, 2).Range.Text = nbFailedTests.ToString();

            var testListBookmarkRange = oDoc.Bookmarks[oEndOfDoc].Range;

            foreach (TestCategory category in TestList)
            {
                //category.ShouldExecuteTest
                object objrangePara = oDoc.Bookmarks[oEndOfDoc].Range;
                //object objrangPara2 = oDoc.Bookmarks[oEndOfDoc].Range;
                //objrangePara.Select();
                Word.Range rangetest = (Word.Range)objrangePara;
                rangetest.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);

                var objpara = oDoc.Content.Paragraphs.Add(ref objrangePara);
                //objpara.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);

                //objpara.Format = new Word.ParagraphFormat();
                //objpara.Format.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);
                //objpara.Range.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);
                //objpara.Range.Text = String.Format("{0}: {1}{2}", category.ID, category.Name, Environment.NewLine);
                rangetest.Text = String.Format("{0}: {1}{2}", category.ID, category.Name, Environment.NewLine);
                //objpara.Range.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);
                //objpara.Format.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);


                foreach (Test test in category.TestList)
                {
                    testListBookmarkRange = oDoc.Bookmarks[oEndOfDoc].Range;

                    Word.Table tbl = oDoc.Tables.Add(testListBookmarkRange, 3, 2);
                    tbl.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    tbl.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
                    tbl.Cell(1, 1).Range.Text = test.ID.ToString();
                    tbl.Cell(1, 2).Range.Text = test.Name;
                    tbl.Cell(2, 1).Range.Text = "Result";
                    if (test.Result != null)
                        tbl.Cell(2, 2).Range.Text = test.Result.Pass ? "Pass" : "Fail";
                    tbl.Cell(3, 1).Range.Text = "Comment";
                    if (test.Result != null)
                        tbl.Cell(3, 2).Range.Text = test.Result.Message;
                    objrangePara = oDoc.Bookmarks[oEndOfDoc].Range;
                    objpara = oDoc.Content.Paragraphs.Add(ref objrangePara);
                    objpara.Range.Text = Environment.NewLine;
                    //test.TestItem.cbRunTest.Checked

                }
            }

            oDoc.TablesOfContents[1].Update();

            object pathtofile = @"C:\TestLab\test.docx";
            oDoc.SaveAs2(ref pathtofile);

            oDoc.Close();
            oWord.Quit();
            GC.Collect();
        }
Run Code Online (Sandbox Code Playgroud)

Cin*_*ter 3

以下方法对我有用。与问题中的代码相反,以下示例

  • 仅适用于Word.Range对象
  • 折叠范围以附加新内容
  • 用于InsertAfter("\n")插入新段落
  • 在应用样式之前添加文本

请注意,如果您打算在使用任何样式格式化的文本后插入表格,Normal则应插入一个新段落并使用该样式对其进行格式化Normal,然后插入表格。否则,如果您使用表格样式,则可能会遇到表格格式问题。

object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
foreach (string s in lst)
{
    Word.Range rngEndOfDoc = oDoc.Bookmarks[oEndOfDoc].Range;
    rngEndOfDoc.InsertAfter("\n");
    rngEndOfDoc.Collapse(ref oCollapseEnd);
    rngEndOfDoc.Text = s;
    rngEndOfDoc.set_Style(Word.WdBuiltinStyle.wdStyleHeading2);
}
Run Code Online (Sandbox Code Playgroud)