2013-04-24 2 views
6

간단한 샘플 Word 문서를 생성하는 샘플 핸들러를 만듭니다.
이 문서의 의지가 텍스트를 포함 안녕하세요 세계Open XML을 사용하여 워드 문서를 만듭니다.

이 내가 만든 Word 문서를 가지고 내가 사용하는 코드 (C# .NET 3.5),
이지만에는 텍스트 크기가 0도 없다.
어떻게 해결할 수 있습니까?

public class HandlerCreateDocx : IHttpHandler 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     using (MemoryStream mem = new MemoryStream()) 
     { 
      // Create Document 
      using (WordprocessingDocument wordDocument = 
       WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true)) 
      { 
       // Add a main document part. 
       MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); 

       // Create the document structure and add some text. 
       mainPart.Document = new Document(); 
       Body body = mainPart.Document.AppendChild(new Body()); 
       Paragraph para = body.AppendChild(new Paragraph()); 
       Run run = para.AppendChild(new Run()); 
       run.AppendChild(new Text("Hello world!")); 
       mainPart.Document.Save(); 
       // Stream it down to the browser 
       context.Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx"); 
       context.Response.ContentType = "application/vnd.ms-word.document"; 
       CopyStream(mem, context.Response.OutputStream); 
       context.Response.End(); 
      } 
     } 
    } 

    // Only useful before .NET 4 
    public void CopyStream(Stream input, Stream output) 
    { 
     byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size 
     int bytesRead; 

     while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) 
     { 
      output.Write(buffer, 0, bytesRead); 
     } 
    } 
} 
+1

Open XML 생산성 도구를 사용하여 문서를 디버깅하는 것이 좋습니다. 또한 먼저 Word에서 문서를 만든 다음이 도구를 사용하여 문서를 만들 코드를 제공하십시오. – juharr

답변

2

(사용하는 CopyTo는 .NET 4.0 이상에서만 사용할 수 있기 때문에 나는. CopyStream 방법을 사용) 나는 그것이 작동하도록 코드를 약간 변형했다. 다운로드를 저장 한 후에 올바르게 열 수 있습니다. 제 수정 된 내용을 참조하십시오. 희망이 도움이됩니다.

using (MemoryStream documentStream = new MemoryStream()) 
{ 
    using (WordprocessingDocument myDoc = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document, true)) 
    { 
     // 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(); 
     myDoc.Close(); 
     context.Response.ClearContent(); 
     context.Response.ClearHeaders(); 
     context.Response.ContentEncoding = System.Text.Encoding.UTF8; 
     SetContentType(context.Request, context.Response, "Simple.docx"); 
     documentStream.Seek(0, SeekOrigin.Begin); 
     documentStream.CopyTo(context.Response.OutputStream); 
     context.Response.Flush(); 
     context.Response.End(); 
    } 
} 
+0

답변이 중복되었습니다. 그리고 행동을 바꾸지 않는 많은 쓸모없는 선을 우리에게 던지십시오. 나는 당신이 당신의 대답을 삭제하는 것이 좋습니다. – SandRock

8

외부 USING 블록에 스트리밍 코드를 넣으면됩니다.

이렇게하면 WordprocessingDocument.Close (Dispose 메서드를 통해) 호출이 발생합니다.

public void ProcessRequest(HttpContext context) 
{ 
    using (MemoryStream mem = new MemoryStream()) 
    { 
     // Create Document 
     using (WordprocessingDocument wordDocument = 
      WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true)) 
     { 
      // Add a main document part. 
      MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); 

      // Create the document structure and add some text. 
      mainPart.Document = new Document(); 
      Body body = mainPart.Document.AppendChild(new Body()); 
      Paragraph para = body.AppendChild(new Paragraph()); 
      Run run = para.AppendChild(new Run()); 
      run.AppendChild(new Text("Hello world!")); 
      mainPart.Document.Save(); 
     } 

     context.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; 
     context.Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx"); 
     mem.Seek(0, SeekOrigin.Begin); 
     mem.CopyTo(context.Response.OutputStream); 
     context.Response.Flush(); 
     context.Response.End(); 
    } 
} 
+0

좋습니다. 나는 당신이 여기에 게시하는 것처럼 해결책을 찾았지만 꽤 늦게 보입니다. –

+0

우리는 여기서 누락 된 점을 고려할 수 있습니다 : wordProcessingDocument는 스트림으로 보내기 전에 닫아야합니다. 스트림은 처음부터 시작되어야합니다. 여기에 귀하의 게시물 솔루션을 주셔서 감사합니다. –

관련 문제