代码之家  ›  专栏  ›  技术社区  ›  Bluetarsky

如果不更改下一段落的样式,则无法使用Word interop更改超链接样式

  •  0
  • Bluetarsky  · 技术社区  · 12 年前

    我有一份格式类似于

    Section Heading 1
        Paragraph 1
        ...
        Paragraph N
        Sub Heading 1
        Paragraph 1
        ...
        Paragraph N
    

    我想做的是从标题向参考文档添加超链接。我可以添加超链接并将样式应用于链接,但样式将应用于节的第1段以及超链接。

    注意:WordApp是Microsoft.Office.Interop.Word.Application的单例包装。HyperlinkDestionation类只保存书签名称和包含书签的文件的路径。

    private void LinkHeadings(string file)
    {
         Document doc = WordApp.Open(file);
    
         for (int i = 1; i <= proposal.Paragraphs.Count; i++)
         {
            HyperlinkDestination dest = null;
    
            Paragraph paragraph = proposal.Paragraphs[i];
            paragraph.Range.Select();
            Style style = (Style)paragraph.get_Style();
            string styleString = ((Style)paragraph.get_Style()).NameLocal;
            string headingText = paragraph.Range.Text.Split(' ')[0];
            if (styleString.Contains("Heading"))
            {
               dest = _hyperlinkDestinations.Find(x => x.HyperlinkText == headingText);
            }
    
            if (dest != null)
            {
               Hyperlink link = WordApp.ActiveWindow.Document.Hyperlinks.Add(WordApp.Selection.Range, Address: dest.FilePath, SubAddress: dest.bookmarkName, TextToDisplay: WordApp.Selection.Text);
               link.Range.set_Style(style);
            }
         }
    
         WordApp.Close(true);
      }
    

    我的猜测是,这与超链接锚点有关。我也尝试过先删除标题,然后插入超链接,但结果也一样。

    1 回复  |  直到 12 年前
        1
  •  1
  •   user1379931 user1379931    12 年前

    基本问题是,在Word插入的超链接字段中包含段落标记。当显示超链接字段结果时,即节标题1段落时,该分段标记将被隐藏。实际上将成为第1款的一部分。将样式应用于所选内容时,整个段落都将受到影响。

    我不打算在这里提供C#,但这里有一些建议 a.通常,在可能的情况下,使用Word中的Range对象比使用Selection更好,您应该可以在这里这样做。 b.如果将超链接应用到没有段落标记的段落,则段落样式将保持不变,因此不需要重新应用 c.因此,不要使用以“paragraph.Range.Select()”开头的代码,您应该能够使用类似的代码(我让您正确使用c#语法-也许您可以编辑此消息)

    Range r = Paragraph.Range();
    string headingText = r.Text.Split(' ')[0];
    if (styleString.Contains("Heading"))
    // you shoul probably also tst for an empty paragraph here before inserting anything (I leave it to you)
    {
        dest = _hyperlinkDestinations.Find(x => x.HyperlinkText == headingText);
    }
    
    if (dest != null)
    {
        // Move the end of the range one character towards the beginning
        r.MoveEnd(Word.WdUnits.WdCharacter,-1)
        Hyperlink link = WordApp.ActiveWindow.Document.Hyperlinks.Add(r, Address: dest.FilePath, SubAddress: dest.bookmarkName, TextToDisplay: r.Text);
    }
    

    如果您的代码需要在国际上运行 只有 需要检查具有内置样式类型的段落标题1...标题9,然后最好比较style.Type,看看它是否是这9种样式类型之一。如果您需要包含名为“Heading something”的其他样式类型,那么您可能需要同时检查style.Type和名称。