Sherry8212
Sherry8212

Reputation: 77

OpenXML word document - open template, edit and download

I need to grap a word template, replace certain words and then download the document for the user - don't need to save to file. I've got the code from MS, got the document into a StreamReader to read the contents and replace, but I don't know how to get the StreamReader back into the memorystream to download.

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

Upvotes: 1

Views: 1675

Answers (2)

Sherry8212
Sherry8212

Reputation: 77

Got the edited document to download with this -

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

Upvotes: 0

FortyTwo
FortyTwo

Reputation: 2639

Read this: 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);
        }
    }
}

Upvotes: 0

Related Questions