2016-07-25 84 views
0

我在文檔中有大約10 MERGEFIELD,我試圖用某些值替換文本。這是代碼。C#中的Openxml只更新段落中的第一個MERGEFIELD

using (WordprocessingDocument document = WordprocessingDocument.Open(destinationFileName, true)) 
      { 
       document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); 
       MainDocumentPart docPart = document.MainDocumentPart; 
       docPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(destinationFileName, UriKind.RelativeOrAbsolute)); 
       docPart.Document.Save(); 

       IEnumerable<FieldChar> fldChars = document.MainDocumentPart.RootElement.Descendants<FieldChar>(); 
       if (fldChars == null) { return; } 

       string fieldList = string.Empty; 
       FieldChar fldCharStart = null; 
       FieldChar fldCharEnd = null; 
       FieldChar fldCharSep = null; 
       FieldCode fldCode = null; 
       string fldContent = String.Empty; 
       int i = 1; 
       foreach(var fldChar in fldChars) 
       { 

        System.Diagnostics.Debug.WriteLine(i + ": " + fldChar); 
        i++; 

        string fldCharPart = fldChar.FieldCharType.ToString(); 
        System.Diagnostics.Debug.WriteLine("Field Char Length: " + fldChar.Count()); 
        System.Diagnostics.Debug.WriteLine("Field Char part: " + fldCharPart); 

        switch(fldCharPart) 
        {  
         case "begin": // start of the field 
          fldCharStart = fldChar; 
          System.Diagnostics.Debug.WriteLine("Field Char Start: " + fldCharStart); 
          // get the field code, which will be an instrText element 
          // either as sibling or as a child of the parent sibling 

          fldCode = fldCharStart.Parent.Descendants<FieldCode>().FirstOrDefault(); 
          System.Diagnostics.Debug.WriteLine("Field Code: " + fldCode); 

          if (fldCode == null) 
          { 
           fldCode = fldCharStart.Parent.NextSibling<Run>().Descendants<FieldCode>().FirstOrDefault(); 
           System.Diagnostics.Debug.WriteLine("New Field Code: " + fldCode); 
          } 

          if (fldCode != null && fldCode.InnerText.Contains("MERGEFIELD")) 
          { 
           fldContent = getFieldValue(query, prescriber, fldCode.InnerText); 
           fieldList += fldContent + "\n"; 
           System.Diagnostics.Debug.WriteLine("Field content: " + fldContent); 

          } 
          break; 

         case "end": // end of the field 
          fldCharEnd = fldChar; 
          System.Diagnostics.Debug.WriteLine("Field char end: " + fldCharEnd); 
          break; 

         case "separate": // complex field with text result 
          fldCharSep = fldChar; 
          break; 

         default: 
          break; 

        } 

        if((fldCharStart != null) && (fldCharEnd != null)) 
        { 
         if(fldCharSep != null) 
         { 
          Text elemText = (Text)fldCharSep.Parent.NextSibling().Descendants<Text>().FirstOrDefault(); 
          elemText.Text = fldContent; 
          System.Diagnostics.Debug.WriteLine("Element text: " + elemText); 

          // Delete all field chas with their runs 
          DeleteFieldChar(fldCharStart); 
          DeleteFieldChar(fldCharEnd); 
          DeleteFieldChar(fldCharSep); 
          fldCode.Remove(); 
         } 
         else 
         { 
          Text elemText = new Text(fldContent); 
          fldCode.Parent.Append(elemText); 
          fldCode.Remove(); 
          System.Diagnostics.Debug.WriteLine("Element Text !sep: " + elemText); 

          DeleteFieldChar(fldCharStart); 
          DeleteFieldChar(fldCharEnd); 
          DeleteFieldChar(fldCharSep); 
         } 

         fldCharStart = null; 
         fldCharEnd = null; 
         fldCharSep = null; 
         fldCode = null; 
         fldContent = string.Empty; 
        } 
       } 
       System.Diagnostics.Debug.WriteLine("Field list: " + fieldList); 
      } 

它在某種程度上起作用。問題是段落中有多個字段。在本文檔的一段中我有大約4個合併字段,之後的每個段落都有一個字段。只有段落中的第一個合併字段正在更新,而段落中的其餘字段未被觸及。然後,它移動到下一個段落並尋找該字段。我怎樣才能解決這個問題?

回答

2

看起來你已經完成了一個簡單的Mailmerge替換。除了循環瀏覽段落外,您還可以在文檔中獲取所有的mailmerge字段並替換它們。

private const string FieldDelimeter = " MERGEFIELD "; 

    foreach (FieldCode field in doc.MainDocumentPart.RootElement.Descendants<FieldCode>()) 
    { 
     var fieldNameStart = field.Text.LastIndexOf(FieldDelimeter, System.StringComparison.Ordinal); 
     var fieldName = field.Text.Substring(fieldNameStart + FieldDelimeter.Length).Trim(); 

     foreach (Run run in doc.MainDocumentPart.Document.Descendants<Run>()) 
     { 
       foreach (Text txtFromRun in run.Descendants<Text>().Where(a => a.Text == "«" + fieldName + "»")) 
       {        
        txtFromRun.Text = "Replace what the merge field here"; 
       } 
     } 
    } 


    doc.MainDocumentPart.Document.Save(); 

doc是WordprocessingDocument類型。

無論段落中的字段數量如何,這將替換所有合併字段。

+0

這沒有奏效。它不會用值替換字段。 fieldName在我的字段中顯示爲'fieldName \ * MERGEFORMAT',它可以與它有任何關係嗎?但即使當我用'\ * MERGEFORMAT'替換「<<」+ fieldName +「>>」時,它仍然不會進入第二個foreach循環。有什麼建議麼? – user1828605

+0

這是正確的答案。我在提取字段名稱時犯了一個錯誤。我沒有做Trim(),導致fieldname後面的空格與文本不匹配。即使在完成Trim()和調試之後,我仍然遇到了錯誤,因爲我已經對修剪後的數據再次進行了子字符串處理。現在正在工作。感謝您向我展示如何做到這一點。我覺得現在我更瞭解它。 – user1828605

+0

MERGEFIELD中的「fldSimple」如何處理?我有使用MERGEFIELD生成超鏈接的情況。 – par