0
替换文本我有,我们作为一个模板word文档,我试图寻找在C#的方式来搜索特定的文字,并用超链接替换它。例如:超链接的Microsoft Word
[FacebookPage1]将与Facebook进行更换,并点击会带他们到Facebook页面时。我们有超过100个不同的链接来循环和替换,所以我需要自动化它。我找到了用其他文字替换文本的方法,但是没有找到用超链接代替文本的方法。这可能吗?
替换文本我有,我们作为一个模板word文档,我试图寻找在C#的方式来搜索特定的文字,并用超链接替换它。例如:超链接的Microsoft Word
[FacebookPage1]将与Facebook进行更换,并点击会带他们到Facebook页面时。我们有超过100个不同的链接来循环和替换,所以我需要自动化它。我找到了用其他文字替换文本的方法,但是没有找到用超链接代替文本的方法。这可能吗?
这是你可以尝试的东西。假设您的模板文档中包含以下内容:
社交媒体:[FacebookPage1] [TwitterPage1] | [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。
这个伟大的工程与例外的我的一个非营利性的工作,所以我们将无法得到许可在这个时候。谢谢,但我将不得不继续搜索免费选项。 – JW12689