2016-12-22 1 views
1

워드 문서 내에서 하이퍼 링크를 수정하려고합니다. 하이퍼 링크는 원래 외부 문서의 책갈피를 가리 킵니다. 내가하고 싶은 것은 같은 앵커로 내부 북마크를 가리 키도록 변경하는 것입니다.openxml로 하이퍼 링크 수정

다음 코드는 내가 사용하는 코드입니다. 변수가 무엇인지 알았지 만 저장된 문서를 보면 원본과 정확하게 같습니다.

내 기회가 지속되지 않는 이유는 무엇입니까? 당신이 스트림을 쓸 때 당신은 아직 OpenXmlPackage를 저장하지 않은

// 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(); 

답변

1

... 명시 적으로

// 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 방법 상태 :

가 저장하고 OPENXML 패키지를 닫 플러스의 모든 기본 부분 스트림.

또한 Dispose가 호출 될 때 OpenXMLPackage가 저장 될 경우 true로 AutoSave 속성을 설정할 수 있습니다. 위에 나온 문 using은 그러한 일이 일어날 것을 보장합니다.

+0

정말 고마워요. 이제 Word에서 내부 북마크에 하이퍼 링크를 추가 할 때 URL이 없으며 텍스트 앞부분에 "#"가 붙습니다. "#서표". "C : \ TEMPO \ smartbook \ test.docx"를 지정하는 대신 자체 URL을 어떻게 만들 수 있는지 알고 싶습니까? –