我需要抓一个单词模板,替换某些单词,然后为用户下载文档 - 不需要保存到文件。我从MS获得了代码,将文档导入StreamReader以读取内容并替换,但我不知道如何将StreamReader重新导入内存流进行下载。
byte[] byteArray = System.IO.File.ReadAllBytes(path);
using (MemoryStream mem = new MemoryStream())
{
mem.Write(byteArray, 0, (int)byteArray.Length);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true))
{
string docText = "";
StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream());
using (sr)
{
docText = sr.ReadToEnd();
}
docText = docText.Replace("<UserName>", model.UserName );
}
//How to I get the docText back into the MemoryStream to download:-
return (ActionResult)File(mem.ToArray(), "application/msword");
阅读本文:How to Search and replace text in a document part Open XML SDK
// To search and replace content in a document part.
public static void SearchAndReplace(string document)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
}
已编辑的文档可以下载 -
doc.MainDocumentPart.Document.Save();
long current = memoryStream.Position;
memoryStream.Position = 0;
Response.AppendHeader("Content-Disposition", "attachment;filename=NewDocument.docx");
Response.ContentType = "application/vnd.ms-word.document";
memoryStream.CopyTo(Response.OutputStream);
Response.End();
memoryStream.Close();
fileStream.Close();