2015-04-07 97 views
2

我想創建一個基於帶內容控件的模板的新Word文檔。C#使用OpenXml填充單詞模板

我需要填寫這些內容控件(文本)。

我只發現如何生成一個新的Word文檔,但不是基於模板。

您有任何鏈接或教程嗎?

也許我錯了使用OpenXml來填充模板?

 // Create a Wordprocessing document. 
     using (WordprocessingDocument myDoc = 
       WordprocessingDocument.Create("d:/dev/test.docx", 
          WordprocessingDocumentType.Document)) 
     { 
      // Add a new main document part. 
      MainDocumentPart mainPart = myDoc.AddMainDocumentPart(); 
      //Create Document tree for simple document. 
      mainPart.Document = new Document(); 
      //Create Body (this element contains 
      //other elements that we want to include 
      Body body = new Body(); 
      //Create paragraph 
      Paragraph paragraph = new Paragraph(); 
      Run run_paragraph = new Run(); 
      // we want to put that text into the output document 
      Text text_paragraph = new Text("Hello World!"); 
      //Append elements appropriately. 
      run_paragraph.Append(text_paragraph); 
      paragraph.Append(run_paragraph); 
      body.Append(paragraph); 
      mainPart.Document.Append(body); 
      // Save changes to the main document part. 
      mainPart.Document.Save(); 
     } 

回答

0

使用OpenXML是正確的方法,因爲您可以在不需要安裝MS Word的情況下操作文檔 - 思考服務器場景。但是,它的學習曲線是陡峭且乏味的。在我看來,最好的方法是要求預算購買第三方工具包,專注於業務領域,而不是OpenXML調整。

在您的示例中,您在Word中有一個模板,並且想要用數據更新(合併)它。我已經爲Docentric Toolkit做了一些這方面的工作,並且工作得很好。一旦你瞭解它如何工作的基礎知識,你可以快速創建解決方案。如果你在DT遇到困難,不會讓你失望。請參閱此鏈接(http://www.codeproject.com/Articles/759408/Creating-Word-documents-in-Net-using-Docentric-Too)瞭解如何使用它。默認情況下,它會創建.docx,但您也可以獲得固定的最終文檔(pdf或xps)。