2011-07-25 25 views
1

添加MERGEFIELDS是否有可能加入MERGEFIELDS到現有.docx文檔,而無需使用互操作,僅利用從代碼隱藏開放式的SDK處理?動態現有的docx文檔

回答

1

是的,這是可能的,我創建了下面,你只是簡單地通過要分配給合併字段名的小方法,它爲您創建它。 下面的代碼是創建一個新的文件,但它應該很容易使用的方法追加到現有的文檔,希望這可以幫助你:

using System; 
using DocumentFormat.OpenXml; 
using DocumentFormat.OpenXml.Packaging; 
using DocumentFormat.OpenXml.Wordprocessing; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      using (WordprocessingDocument package = WordprocessingDocument.Create("D:\\ManualMergeFields.docx", WordprocessingDocumentType.Document)) 
      { 
       package.AddMainDocumentPart(); 

       Paragraph nameMergeField = CreateMergeField("Name"); 
       Paragraph surnameMergeField = CreateMergeField("Surname"); 

       Body body = new Body(); 
       body.Append(nameMergeField); 
       body.Append(surnameMergeField); 
       package.MainDocumentPart.Document = new Document(new Body(body)); 
      } 
     } 

     static Paragraph CreateMergeField(string name) 
     { 
      if (!String.IsNullOrEmpty(name)) 
      { 
       string instructionText = String.Format(" MERGEFIELD {0} \\* MERGEFORMAT", name); 
       SimpleField simpleField1 = new SimpleField() { Instruction = instructionText }; 

       Run run1 = new Run(); 

       RunProperties runProperties1 = new RunProperties(); 
       NoProof noProof1 = new NoProof(); 

       runProperties1.Append(noProof1); 
       Text text1 = new Text(); 
       text1.Text = String.Format("«{0}»", name); 

       run1.Append(runProperties1); 
       run1.Append(text1); 

       simpleField1.Append(run1); 

       Paragraph paragraph = new Paragraph(); 
       paragraph.Append(new OpenXmlElement[] { simpleField1 }); 
       return paragraph; 
      } 
      else return null; 
     } 
    } 
} 

你可以從這個網址下載開放式XML生產力工具(如果您還沒有它)http://www.microsoft.com/download/en/details.aspx?id=5124 此工具具有「反映代碼」功能。因此,您可以手動創建合併域MS Word文件,然後打開該文檔與生產力工具 ,看看如何做到這一點在代碼中的C#代碼示例!這是非常有效的,我用這個確切的工具來創建示例above.Good運氣