2013-03-21 5 views
2

콘솔에 파일을 만드는 기본 코드가 있습니다 (아래 참조).하지만 ActionResult로 XML 문서를 반환해야하므로 MVC 앱을 작성하고 있습니다. 웹에서 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"); 
    } 
관련 문제