1

I'm trying to serve a word document (docx) from an asp.net page using the following code

    protected void Page_Load(object sender, EventArgs e)
    {

        MemoryStream document = new MemoryStream();
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document))
        {
            MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
            SetMainDocumentContent(mainPart);
        }

        string fileName = "MsWordSample.docx";
        Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
        Response.OutputStream.Write(document.ToArray(), 0, document.ToArray().Length);
    }

    public static void SetMainDocumentContent(MainDocumentPart part)
    {
        const string docXml =
         @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> 
        <w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
        <w:body>
            <w:p>
                <w:r>
                    <w:t>Hello world!</w:t>
                </w:r>
            </w:p>
        </w:body>
        </w:document>";

        using (Stream stream = part.GetStream())
        {
            byte[] buf = (new UTF8Encoding()).GetBytes(docXml);
            stream.Write(buf, 0, buf.Length);
        }
    }

but I get the following message when trying to open the file: "the file {file name} cannot be opened because there are problems with the content"

I then get an option to recover the document which actually fixes the document.

Am I leaving something out?

Fikre
  • 555
  • 2
  • 7
  • 16

1 Answers1

0

That error message you're getting means the underlying XML doesn't conform to the schema in some way. This could be caused by having elements in the wrong order, forgetting a parent to an element, adding a wrong attribute, forgetting required elements, etc. I recommend downloading the Open XML SDK 2.0 Productivity Tool, create a test file, and then opening that up to see what the XML should be. Then compare that file to the one you are creating to see what is missing.

amurra
  • 15,221
  • 4
  • 70
  • 87
  • Another helpful tools is the `OpenXmlValidator`. It will show you all the errors in your XML structure. HUGE help in my development. – CoderMarkus Oct 31 '12 at 19:48
  • You're right, and the reason for the invalid XML is that I forgot to add Response.End() – Fikre Aug 15 '13 at 07:26