2015-04-07 151 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)。