7

Is there a way of providing a download in an ASP.Net Page for a freshly generated OpenXML (docx) file without saving it in a temporary folder?

On MSDN I only found a tutorial for using a temp file but I thought about using the WordprocessingDocument.MainDocumentPart.GetStream() and directly writing the stream out.

Kuepper
  • 992
  • 13
  • 39
  • This looks like a duplicate of this question. http://stackoverflow.com/questions/393647/response-content-type-as-csv You should be able to use the same solution by writing your data directly to the response. – kareem Apr 19 '11 at 00:37

2 Answers2

12

When you create the document use a MemoryStream as the backing store. Then create and close the document normally and serve the contents of the memory stream to the client.

using(var stream = new MemoryStream())
{
    using(var doc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true) 
    {
        ...
    }
    stream.Position = 0;
    stream.CopyTo(Response.OutputStream);
}

Do not just grab the MainDocumentPart because, as the name implies, this is just one part of the document package, not everything.

You'll also need to set response headers for content type and disposition.

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
1

Stream.CopyTo() in .NET 4.0 might help you out here.

WordprocessingDocument.MainDocumentPart.GetStream().CopyTo(Response.OutputStream);

You'll still need to set the headers for MIME type, content-disposition and so on.

tomfanning
  • 9,552
  • 4
  • 50
  • 78