我正在创建一个示例处理程序来生成简单的 Word 文档。
该文档将包含文本Hello world
这是我使用的代码(C# .NET 3.5),
我创建了 Word 文档,但其中没有文本,大小为 0。
我该如何修复它?
(我使用CopyStream方法,因为 CopyTo 仅在 .NET 4.0 及更高版本中可用。)
public class HandlerCreateDocx : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
using (MemoryStream mem = new MemoryStream())
{
// Create Document
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text("Hello world!"));
mainPart.Document.Save();
// Stream it down to the browser
context.Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
context.Response.ContentType = "application/vnd.ms-word.document";
CopyStream(mem, context.Response.OutputStream);
context.Response.End();
}
}
}
// Only useful before .NET 4
public void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}