【发布时间】:2019-08-16 22:23:13
【问题描述】:
我需要在 ASP.NET 控制器方法中将文档作为 MemoryStream 返回以在网页上下载它。我不想将此文档保存在文件中,然后将其作为 MemoryStream 读取并返回。 注意:重载方法 WordprocessingDocument.CreateFromTemplate(template) 没有流选项 vs WordprocessingDocument.Create(stream, ...)
保存临时文件的解决方案如下。
public static MemoryStream GetWordDocumentFromTemplate()
{
string tempFileName = Path.GetTempFileName();
var templatePath = AppDomain.CurrentDomain.BaseDirectory + @"Controllers\" + templateFileName;
using (var document = WordprocessingDocument.CreateFromTemplate(templatePath))
{
var body = document.MainDocumentPart.Document.Body;
//add some text
Paragraph paraHeader = body.AppendChild(new Paragraph());
Run run = paraHeader.AppendChild(new Run());
run.AppendChild(new Text("This is body text"));
OpenXmlPackage savedDoc = document.SaveAs(tempFileName); // Save result document, not modifying the template
savedDoc.Close(); // can't read if it's open
document.Close();
}
var memoryStream = new MemoryStream(File.ReadAllBytes(tempFileName)); // this works but I want to avoid saving and reading file
//memoryStream.Position = 0; // should I rewind it?
return memoryStream;
}
【问题讨论】:
-
我已经有一段时间没有这样做了,但我相信您想要做的是获取响应流并在该流上构建 WordprocessingDocument。然后设置 mime 类型等并将流返回给客户端。
标签: c# ms-word openxml memorystream