OpenXML Word文档-打开模板,编辑和下载

时间:2018-08-18 20:40:27

标签: ms-word openxml streamreader memorystream

我需要掌握一个单词模板,替换某些单词,然后为用户下载文档-无需保存到文件。我已经从MS获得了代码,将文档放入了StreamReader中以读取内容并替换,但是我不知道如何将StreamReader返回到内存流中进行下载。

nullptr_t

2 个答案:

答案 0 :(得分:0)

阅读: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);
        }
    }
}

答案 1 :(得分:0)

获得编辑后的文档以下载-

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();