将Word预定义样式应用于C#

时间:2018-09-21 13:27:05

标签: c# visual-studio ms-word 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";

enter image description here

这在视觉上应用了样式,但是当我更新它时它没有出现在目录中。当我在Word中选择文本时,它说它具有普通的文本样式,即使在视觉上具有Heading2样式。

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

在这里您可以看到样式在视觉上还可以,但是Word将其检测为普通文本: enter image description here enter image description here

完整的代码清单:

        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();
        }

3 个答案:

答案 0 :(得分:1)

以下方法适用于我。与“问题”中的代码相反,以下示例

  • 仅与<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input data-input-search class="form-control visible" type="search" name="q" autofocus="" autocomplete="off" id="input" placeholder="Search..."> <button class="btn btn-primary btn-circle" type="submit" value="Google" formaction="http://www.google.de/search" target="_blank" value="Google"><span><i class="fa fa-google animated" ></i></span>Google</button> <button class="btn btn-primary btn-circle" type="submit" value="YouTube" formaction="https://www.youtube.com/search" target="_blank"><span><i class="fa fa-youtube-play animated"></i></span>YouTube</button> <button class="btn btn-primary btn-circle" type="submit" value="Amazon" formaction="https://www.amazon.de/s/" data-search-input-name="k" target="_blank"><span><i class="fa fa-amazon animated"></i></span>Amazon</button> <button class="btn btn-primary btn-circle" type="submit" value="Google Translate" formaction="https://translate.google.com/#auto/de/" target="_blank"><span><i class="fas fa-language animated"></i></span>Translate</button> <button class="btn btn-primary btn-circle" type="submit" value="Google Images" formaction="http://www.google.com/images?q"><span><i class="fa fa-image animated"></i></span>Images</button> <button class="btn btn-primary btn-circle" type="submit" value="Netflix" formaction="https://www.netflix.com/search?q"><span><i class="fa fa-film animated"></i></span>Netflix</button> <button class="btn btn-primary btn-circle" type="submit" value="Wikipedia" formaction="https://en.wikipedia.org/w/index.php?" data-search-input-name="search"><span><i class="fa fa-wikipedia-w animated"></i></span>Wikipedia</button> </form>个对象一起使用
  • 折叠范围以添加新内容
  • 使用Word.Range插入新段落
  • 使用样式在之前添加文本

请注意,如果您打算在以InsertAfter("\n")以外的其他样式设置格式的文本之后插入表格,则应插入新段落并以Normal样式设置其格式,然后插入表格。否则,如果您使用表格样式,则表格格式可能会遇到问题。

Normal

答案 1 :(得分:0)

不确定是否有解决此问题的方法,但我在将样式链接到段落时遇到了类似的问题。我在文本中用“\n”分隔的行也有问题。下面的代码适用于我,并将样式正确应用于传递的文本,包括换行符,并且样式链接到结果文档中的文本。

using Word = Microsoft.Office.Interop.Word;

public void WritePara(String pText, String pStyle) {
            Word.Paragraph p1 = oDoc.Content.Paragraphs.Add();

            object oStart = oDoc.Content.End - 1;
            p1.Range.Text = pText;
            object oEnd = oDoc.Content.End - 1;
                        
            Word.Range para = oDoc.Range(oStart, oEnd);
            object oStyleName = pStyle;
            para.set_Style(ref oStyleName);
        }

答案 2 :(得分:-1)

首先通过NuGet软件包管理器安装在软件包下面:

Install-Package Microsoft.Office.Interop.Word

现在您可以将自定义样式应用于任何选择范围。

在下面的示例代码中,标题1 样式将应用于“ Test.docx”:文档的第一段。

// Define new application and open MS Word document.
Application app = new Application();
Document doc = app.Documents.Open(@"D:\Test.docx");

// Select first paragraph.
doc.Paragraphs[1].Range.Select();

// Define style as object and assign your custom style as string to it.
object style = "Heading 1";

// Set custom style to selected range
app.Selection.set_Style(ref style);

// Close document and pass true if you want save changes and finally quit from application.
doc.Close(true);
app.Quit();

在这种方法中,将样式应用于任何选择范围之类的任何更改都会在视觉上应用它们产生影响。