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

问题描述 投票:0回答:2

我需要抓一个单词模板,替换某些单词,然后为用户下载文档 - 不需要保存到文件。我从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");
ms-word openxml streamreader memorystream
2个回答
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);
        }
    }
}

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();
© www.soinside.com 2019 - 2024. All rights reserved.