Note that there are some explanatory texts on larger screens.

plurals
  1. POcreate word document with Open XML
    primarykey
    data
    text
    <p>I am creating a sample handler to generate simple Word document.<br> This document will contains the text <strong>Hello world</strong> </p> <p>This is the code I use (C# .NET 3.5),<br> I got the Word document created but there is no text in it, the size is 0.<br> How can I fix it?<br> (I use <strong>CopyStream</strong> method because CopyTo is available in .NET 4.0 and above only.)</p> <pre><code>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)) &gt; 0) { output.Write(buffer, 0, bytesRead); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload