2017-03-21 47 views
0

替換文本我有,我們作爲一個模板word文檔,我試圖尋找在C#的方式來搜索特定的文字,並用超鏈接替換它。例如:超鏈接的Microsoft Word

[FacebookPage1]將與Facebook進行更換,並點擊會帶他們到Facebook頁面時。我們有超過100個不同的鏈接來循環和替換,所以我需要自動化它。我找到了用其他文字替換文本的方法,但是沒有找到用超鏈接代替文本的方法。這可能嗎?

回答

0

這是你可以嘗試的東西。假設您的模板文檔中包含以下內容:

社交媒體:[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」 文件:

output Word document

的是,上述代碼使用 GemBox.Document用於與DOCX文件操縱

注意,它有一個Free and Professional versions

+0

這個偉大的工程與例外的我的一個非營利性的工作,所以我們將無法得到許可在這個時候。謝謝,但我將不得不繼續搜索免費選項。 – JW12689