2013-07-29 5 views
2

OpenXML을 사용하여 Word 템플릿을 수정하는 중입니다.이 템플릿에는 특정 문자 (현재는 더블 쉐브론 (ascii 171 및 187))로 식별 할 수있는 간단한 토큰이 들어 있습니다.Word OpenXML 토큰 텍스트 바꾸기

이 토큰을 내 텍스트로 바꾸고 싶습니다. 텍스트는 여러 줄로 나눌 수 있습니다 (예 : 데이터베이스).

 //read file into memory 
     byte[] docByteArray = File.ReadAllBytes(templateName); 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      //write file to memory stream 
      ms.Write(docByteArray, 0, docByteArray.Length); 

      // 
      ReplaceText(ms); 

      //reset stream 
      ms.Seek(0L, SeekOrigin.Begin); 

      //save output 
      using (FileStream outputStream = File.Create(docName)) 
       ms.CopyTo(outputStream); 
     } 

몸의 내부 텍스트 XML을 검색하는 간단한 방법이 가장 빠른 방법이지만, 여러 줄의 텍스트 삽입을 허용하지 않고 포기하지 않습니다

답변

5

은 첫째로 당신은 템플릿을 열 필요 당신은 더 복잡한 변화로 확장 할 수있는 기초가됩니다.

 using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(ms, true)) 
     { 
      //get all the text elements 
      IEnumerable<Text> texts = wordDoc.MainDocumentPart.Document.Body.Descendants<Text>(); 
      //filter them to the ones that contain the QuoteLeft char 
      var tokenTexts = texts.Where(t => t.Text.Contains(oldString)); 

      foreach (var token in tokenTexts) 
      { 
       //get the parent element 
       var parent = token.Parent; 
       //deep clone this Text element 
       var newToken = token.CloneNode(true); 

       //split the text into an array using a regex of all line terminators 
       var lines = Regex.Split(myNewString, "\r\n|\r|\n"); 

       //change the original text element to the first line 
       ((Text) newToken).Text = lines[0]; 
       //if more than one line 
       for (int i = 1; i < lines.Length; i++) 
       { 
        //append a break to the parent 
        parent.AppendChild<Break>(new Break()); 
        //then append the next line 
        parent.AppendChild<Text>(new Text(lines[i])); 
       } 

       //insert it after the token element 
       token.InsertAfterSelf(newToken); 
       //remove the token element 
       token.Remove(); 
      } 

      wordDoc.MainDocumentPart.Document.Save(); 
     } 

은 기본적으로 당신이 (변경 삽입을 복제 (워드 텍스트의 런의 단락에서 내장) 텍스트 요소를 찾을 수 :

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(ms, true)) 
{ 
    string docText = null; 
    //read the entire document into a text 
    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream())) 
     docText = sr.ReadToEnd(); 

    //replace the text 
    docText.Replace(oldString, myNewString); 

    //write the text back 
    using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))) 
     sw.Write(docText); 
} 

대신 당신은 요소와 구조 작업해야 새로운 Break와 Text 엘리먼트가 필요하다면), 원래 토큰 Text 엘리먼트 뒤에 추가하고 마지막으로 원래 토큰 Text 엘리먼트를 제거한다.

+0

언급하는 것을 잊어 버린 경우, 두 방법 모두 토큰 텍스트의 형식을 상속합니다. 그러나 후자의 접근 방식은 요소 트리 주변에서 작업 할 수 있으므로 변경 가능성을 허용합니다. – cjb110

관련 문제