流式传输OpenXML结果

时间:2012-07-08 07:02:20

标签: openxml

通过使用 OpenXML 来操作 Word 文档(作为模板),服务器应用程序将新内容保存为临时文件,然后将其发送给用户下载

问题是如何将这些内容准备好下载而不将其作为临时文件保存在服务器上?是否可以将 OpenXML 结果保存为byte[]Stream而不是将其另存为文件?

2 个答案:

答案 0 :(得分:2)

您可以创建WordprocessingDocument,然后使用Save()方法将其保存到Stream

http://msdn.microsoft.com/en-us/library/cc882497

答案 1 :(得分:2)

使用此页面: OpenXML file download without temporary file

我将代码更改为此代码:

byte[] result = null;
byte[] templateBytes = System.IO.File.ReadAllBytes(wordTemplate);
using (MemoryStream templateStream = new MemoryStream())
{
    templateStream.Write(templateBytes, 0, (int)templateBytes.Length);
    using (WordprocessingDocument doc = WordprocessingDocument.Open(templateStream, true))
    {
        MainDocumentPart mainPart = doc.MainDocumentPart;           
        ...         
        mainPart.Document.Save();
        templateStream.Position = 0;
        using (MemoryStream memoryStream = new MemoryStream())
        {
            templateStream.CopyTo(memoryStream);
            result = memoryStream.ToArray();
        }
    }
}