2012-02-24 65 views
2

我读过一些提到填充单词文档的帖子,但我需要使用C#填充Word文档(Office 2007)。例如,我想要一个带有标签[NAME]的单词文档,在C#中使用该标签来放置我的值,并在ASP.NET MVC3控制器中执行所有操作。任何想法?在ASP.NET MVC3中使用C#填充单词模板

回答

3

您可以使用Microsoft提供的OpenXML SDK来操作Word文档。这里有一个nice article(它实际上是一系列3篇文章中的第三篇),并附有一些例子。

+0

很酷。我也发现[这个链接](http://seroter.wordpress.com/2009/12/23/populating-word-2007-templates-through-open-xml/)非常有用。但仍然没有得到它的工作,因为[这](http://stackoverflow.com/questions/9433332/open-xml-sdk-2-0):( – 2012-02-24 15:33:30

0

你可以这样做: - 介绍“荣誉徽章”到Word文档模板 - 工作在您的Word模板 的副本 - 修改纹章从C#代码值和保存或打印文件。

要当心用正确释放你的话的过程,如果你把你的应用程序:)从问题中提取

0

OP的解决方案的几个文件:

的解决方案,我发现是这样的:

static void Main(string[] args) 
{ 
    Console.WriteLine("Starting up Word template updater ..."); 

    //get path to template and instance output 
    string docTemplatePath = @"C:\Users\user\Desktop\Doc Offices XML\earth.docx"; 
    string docOutputPath = @"C:\Users\user\Desktop\Doc Offices XML\earth_Instance.docx"; 

    //create copy of template so that we don't overwrite it 
    File.Copy(docTemplatePath, docOutputPath); 

    Console.WriteLine("Created copy of template ..."); 

    //stand up object that reads the Word doc package 
    using (WordprocessingDocument doc = WordprocessingDocument.Open(docOutputPath, true)) 
    { 
     //create XML string matching custom XML part 
     string newXml = "<root>" + 
      "<Earth>Outer Space</Earth>" + 
      "</root>"; 

     MainDocumentPart main = doc.MainDocumentPart; 
     main.DeleteParts<CustomXmlPart>(main.CustomXmlParts); 

     //MainDocumentPart mainPart = doc.AddMainDocumentPart(); 

     //add and write new XML part 
     CustomXmlPart customXml = main.AddCustomXmlPart(CustomXmlPartType.CustomXml); 
     using (StreamWriter ts = new StreamWriter(customXml.GetStream())) 
     { 

      ts.Write(newXml); 
     } 

     //closing WordprocessingDocument automatically saves the document 
    } 

    Console.WriteLine("Done"); 
    Console.ReadLine(); 
}