create word document with Open XML

后端 未结 3 898
栀梦
栀梦 2020-12-16 00:28

I am creating a sample handler to generate simple Word document.
This document will contains the text Hello world

This is the code I use (C# .

3条回答
  •  囚心锁ツ
    2020-12-16 01:00

    This works for me, by putting the streaming code in the outer USING block.

    This causes a call to WordprocessingDocument.Close (via the Dispose method).

    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();
        }
    }
    

提交回复
热议问题