如何使用 OpenXml 和 .Net 将 Microsoft Word 网址中的超链接从“http://www.google.com”修改为“MyDoc.docx”?
我可以获取文档中的所有超链接,但找不到要更改的 url 属性。我有这样的事情:
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"C:\Users\Costa\Desktop\AAA.docx", true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
Hyperlink hLink = mainPart.Document.Body.Descendants<Hyperlink>().FirstOrDefault();
}
谢谢
最佳答案
很遗憾,您无法使用 OpenXml 直接更改超链接路径。唯一的方法是找到当前超链接的 HyperlinkRelation 对象并将其替换为具有相同关系 Id 但新超链接路径的 hew 对象:
using DocumentFormat.OpenXml.Wordprocessing;
MainDocumentPart mainPart = doc.MainDocumentPart;
Hyperlink hLink = mainPart.Document.Body.Descendants<Hyperlink>().FirstOrDefault();
if (hLink != null)
{
// get hyperlink's relation Id (where path stores)
string relationId = hLink.Id;
if (relationId != string.Empty)
{
// get current relation
HyperlinkRelationship hr = mainPart.HyperlinkRelationships.Where(a => a.Id == relationId).FirstOrDefault();
if (hr != null)
// remove current relation
{ mainPart.DeleteReferenceRelationship(hr); }
//add new relation with same Id , but new path
mainPart.AddHyperlinkRelationship(new System.Uri(@"D:\work\DOCS\new\My.docx", System.UriKind.Absolute), true, relationId);
}
}
// apply changes
doc.Close();
关于.net - 如何使用 OpenXML 修改 word 超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13082387/