使用 openxml 修改超链接

Modifying Hyperlink with openxml

我正在尝试修改 word 文档中的超链接。超链接最初指向外部文档中的书签。我想要做的是将其更改为指向与同一个锚点相同的内部书签。

这是我使用的代码...当我输入变量时,它似乎可以工作,但当我查看保存的文档时,它与原始文档完全一样。

我的机会没有持续存在的原因是什么?

// read file specified in stream 
MemoryStream stream = new MemoryStream(File.ReadAllBytes("C:\TEMPO\smartbook\text1.docx"));
WordprocessingDocument doc = WordprocessingDocument.Open(stream, true);

MainDocumentPart mainPart = doc.MainDocumentPart;

// The first hyperlink -- it happens to be the one I want to modify 
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 relation 
            // mainPart.AddHyperlinkRelationship(new Uri("C:\TEMPO\smartbook\test.docx"), false, relationId);
        }
    }

    // change hyperlink attributes
    hLink.DocLocation = "#";
    hLink.Id = "";
    hLink.Anchor = "TEST";
}
// save stream to a new file
File.WriteAllBytes("C:\TEMPO\smartbook\test.docx", stream.ToArray());
doc.Close();

您在写入流时尚未保存 OpenXmlPackage ...

// types that implement IDisposable are better wrapped in a using statement
using(var stream = new MemoryStream(File.ReadAllBytes(@"C:\TEMPO\smartbook\text1.docx")))
{
   using(var doc = WordprocessingDocument.Open(stream, true))
   {
      // do all your changes
      // call doc.Close because that SAVES your changes to the stream
      doc.Close(); 
   }
   // save stream to a new file
   File.WriteAllBytes(@"C:\TEMPO\smartbook\test.docx", stream.ToArray());
} 

Close 方法明确指出:

Saves and closes the OpenXml package plus all underlying part streams.

您还可以将 AutoSave 属性 设置为 true,在这种情况下,将在调用 Dispose 时保存 OpenXMLPackage。我在上面使用的 using 声明将保证会发生这种情况。