【发布时间】:2011-07-11 19:57:34
【问题描述】:
我正在尝试使用以下代码从 asp.net 页面提供 word 文档 (docx)
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);
}
}
但我在尝试打开文件时收到以下消息:“文件 {file name} 无法打开,因为内容存在问题”
然后我可以选择恢复实际修复文档的文档。
我是否遗漏了什么?
【问题讨论】:
-
Response.End()修复了我的相同问题。谢谢@Fikre