没有临时文件的OpenXML文件下载

时间:2021-08-05 16:47:16

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?

有没有办法在ASP.Net页面中为新生成的OpenXML(docx)文件提供下载而不将其保存在临时文件夹中?

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.

在MSDN上,我只找到了使用临时文件的教程,但我想过使用WordprocessingDocument.MainDocumentPart.GetStream()并直接写出流。

2 个解决方案

#1


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.

创建文档时,请使用MemoryStream作为后备存储。然后正常创建并关闭文档,并将内存流的内容提供给客户端。

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.

不要只是抓住MainDocumentPart,因为顾名思义,这只是文档包的一部分,而不是一切。

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

您还需要为内容类型和处置设置响应标头。

#2


1  

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

.NET 4.0中的Stream.CopyTo()可能会帮到你。

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

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

您仍然需要为MIME类型,内容处置等设置标头。

#1


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.

创建文档时,请使用MemoryStream作为后备存储。然后正常创建并关闭文档,并将内存流的内容提供给客户端。

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.

不要只是抓住MainDocumentPart,因为顾名思义,这只是文档包的一部分,而不是一切。

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

您还需要为内容类型和处置设置响应标头。

#2


1  

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

.NET 4.0中的Stream.CopyTo()可能会帮到你。

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

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

您仍然需要为MIME类型,内容处置等设置标头。