2013-03-21 84 views
2

我有基本的代码,在控制台中创建文件(见下文)..但我正在写一个MVC应用程序,所以我需要返回该XML文件作为ActionResult ....我一直在寻找网络2小时寻找一个简单的例子,没有运气..如何返回OPENXML Word文档的MVC ActionResult?

什么我添加到这使它成为一个ActionResult?

 string filePath = @"C:\temp\OpenXMLTest.docx"; 
     using (WordprocessingDocument doc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document)) 
     { 
      //// Creates the MainDocumentPart and add it to the document (doc)  
      MainDocumentPart mainPart = doc.AddMainDocumentPart(); 
      mainPart.Document = new Document(
       new Body(
        new Paragraph(
         new Run(
          new Text("Hello World!!!!!"))))); 
     } 

回答

4

下面是一些示例代码。请注意,此代码不会从磁盘加载文件,它会即时创建文件并写入MemoryStream。写入磁盘所需的更改很少。

public ActionResult DownloadDocx() 
    { 
     MemoryStream ms; 

     using (ms = new MemoryStream()) 
     { 
      using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document)) 
      { 
       MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); 

       mainPart.Document = new Document(
        new Body(
         new Paragraph(
          new Run(
           new Text("Hello world!"))))); 
      } 
     } 

     return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Test.docx"); 
    } 
相关问题