word-Dokument erstellen mit Open XML

Erstelle ich ein Probe-handler zu erzeugen, einfaches Word-Dokument.

Dieses Dokument enthält den text Hallo Welt

Dies ist der code den ich verwende (in C# .NET 3.5),

Ich habe das Word-Dokument erstellt, aber es ist kein text drin, die Größe ist 0.

Wie kann ich es beheben?

(Ich benutze CopyStream Methode CopyTo verfügbar ist .NET 4.0 und höher nur.)

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);
        }
    }
}
  • Ich empfehle die Verwendung der Open XML-Produktivitäts-Tool zum Debuggen Ihres Dokuments. Auch sollten Sie das Dokument in Word zuerst und dann das tool verwenden, um geben Sie den code, der das Dokument erstellt wurde.
InformationsquelleAutor Tuyen Nguyen | 2013-04-24
Schreibe einen Kommentar