【问题标题】:Replacing text with hyperlink microsoft word用超链接 microsoft word 替换文本
【发布时间】:2017-04-13 18:54:47
【问题描述】:

我有一个 Word 文档,我们将其用作模板,并试图在 C# 中找到一种方法来搜索特定文本并将其替换为超链接。例如:

[FacebookPage1] 将被 Facebook 替换,点击后会将他们带到 Facebook 页面。我们有超过 100 个不同的链接要循环和替换,所以我需要自动化它。我找到了用其他文本替换文本的方法,但还没有找到用超链接替换文本的方法。这可能吗?

【问题讨论】:

    标签: c# replace ms-word


    【解决方案1】:

    这里有一些你可以尝试的东西。假设您的模板文档中有类似以下内容:

    社交媒体:[FacebookPage1] | [推特第1页] | [GooglePlusPage1] | [LinkedInPage1]

    在这种情况下,您可以使用以下内容将这些占位符替换为超链接:

    // Create collection of "placeholder -> link" pairs.
    var linkData = new Dictionary<string, string>()
    {
        ["FacebookPage1"] = "https://www.facebook.com",
        ["TwitterPage1"] = "https://twitter.com",
        ["GooglePlusPage1"] = "https://plus.google.com",
        ["LinkedInPage1"] = "https://www.linkedin.com"
    };
    
    // Create placeholder regex, the pattern for texts between square brackets.
    Regex placeholderRegex = new Regex(@"\[(.*?)\]", RegexOptions.Compiled);
    
    // Load template document.
    DocumentModel document = DocumentModel.Load("Template.docx");
    
    // Search for placeholders in the document.
    foreach (ContentRange placeholder in document.Content.Find(placeholderRegex).Reverse())
    {
        string name = placeholder.ToString().Trim('[', ']');
        string link;
    
        // Replace placeholder with Hyperlink element.
        if (linkData.TryGetValue(name, out link))
            placeholder.Set(new Hyperlink(document, link, name).Content);
    }
    
    // Save document.
    document.Save("Output.docx");
    

    以下是生成的“Output.docx”文件:

    请注意,上面的代码使用GemBox.Document 来操作DOCX 文件,它有一个Free and Professional versions

    【讨论】:

    • 这很好用,但我为非营利组织工作,因此我们目前无法负担许可费用。谢谢,但我将不得不继续寻找免费选项。
    猜你喜欢
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2023-01-25
    相关资源
    最近更新 更多