我正在創建一個樣本處理程序來生成簡單的Word文檔。
該文件將包含文本世界,你好用Open XML創建Word文檔
這是我創建的Word文檔,我使用的代碼(C#.NET 3.5),
但在它沒有文本,大小爲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);
}
}
}
我推薦使用Open XML Productivity Tool來調試文檔。還要考慮首先在Word中創建文檔,然後使用該工具爲您提供將創建文檔的代碼。 – juharr 2013-04-24 14:36:34