我正在尝试从磁盘读取模板文件并为其添加一个段落。完成后,我想将其作为新文件打开。模板中不应保存更改。我尝试了下面的代码,结果是,模板已通过更改进行了修改,但是在浏览器中打开的文件没有这些更改。显然,我没有得到修改后的流作为响应。我该怎么做,还要避免对模板文件进行更改。
public class DocumentCreator
{
public static void CreateDoc()
{
string strDoc = @"C:\Ash\foo.docx";
string txt = "Bruno Rovani";
using (Stream stream = File.Open(strDoc, FileMode.Open))
{
OpenAndAddToWordprocessingStream(stream, txt);
}
}
public static void OpenAndAddToWordprocessingStream(Stream stream, string txt)
{
// Open a WordProcessingDocument based on a stream.
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(stream, true))
{
// Assign a reference to the existing document body.
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
// Add new text.
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(txt));
// HTTP response
HttpResponse Response = HttpContext.Current.Response;
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
//stream = wordprocessingDocument.MainDocumentPart.GetStream();
stream.Position = 0;
stream.CopyTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
答案 0 :(得分:0)
已解决
添加了wordprocessingDocument.MainDocumentPart.Document.Save();
PS:模板仍在修改中。不要以为有办法避免这种情况,但是由于我将在实际情况下进行查找和替换,因此这对我来说不是一个大问题。
所以功能看起来像
public static void OpenAndAddToWordprocessingStream(Stream stream, string txt)
{
// Open a WordProcessingDocument based on a stream.
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(stream, true))
{
// Assign a reference to the existing document body.
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
// Add new text.
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(txt));
**wordprocessingDocument.MainDocumentPart.Document.Save();**
// HTTP response
HttpResponse Response = HttpContext.Current.Response;
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}