简体   繁体   中英

OpenXML SDK replace text in Template Document

With OpenXML SDK i have created a docx file which i'm using as a template. It needs to replace the words inside the document. Well if i use a document with paragraphs it works. But for text within a tablecell and within a paragraph like a break it's not working. Below my code =>

    protected void btnMail_Click(object sender, EventArgs e)
    {
        string templateDocumentPath = string.Format("{0}\\document.docx", Server.MapPath("~/App_Data"));

        byte[] result = null;
        byte[] templateBytes = System.IO.File.ReadAllBytes(templateDocumentPath);

        using (MemoryStream templateStream = new MemoryStream())
        {
            templateStream.Write(templateBytes, 0, (int)templateBytes.Length);
            using (WordprocessingDocument doc = WordprocessingDocument.Open(templateStream, true))
            {
                MainDocumentPart mainPart = doc.MainDocumentPart;

                var body = doc.MainDocumentPart.Document.Body;
                var paras = body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>();

                var breaks = body.Elements<DocumentFormat.OpenXml.Wordprocessing.Break>();

                foreach (var br in breaks)
                {
                    foreach (var run in br.Elements<Run>())
                    {
                        foreach (var text in run.Elements<Text>())
                        {
                            if (text.Text.Contains("#bNaam#"))
                            {
                                text.Text = text.Text.Replace("#bNaam#", Parameters.Naam);
                                run.AppendChild(new Break());
                            }
                        }
                    }
                }


                foreach (var para in paras)
                {
                    foreach (var run in para.Elements<Run>())
                    {
                        foreach (var text in run.Elements<Text>())
                        {
                            if (text.Text.Contains("bNaam"))
                            {
                                text.Text = text.Text.Replace("bNaam", Parameters.Naam);
                                run.AppendChild(new Break());
                            }

                            if (text.Text.Contains("bAdres"))
                            {
                                text.Text = text.Text.Replace("bAdres", Parameters.Adres);
                                run.AppendChild(new Break());
                            }

                            if (text.Text.Contains("#bPostcode#") && text.Text.Contains("#bGemeente#"))
                            {
                                text.Text = text.Text.Replace("#bPostcode#", Parameters.Postcode);
                                text.Text = text.Text.Replace("#bGemeente#", Parameters.Plaats);
                                run.AppendChild(new Break());
                            }

                            if (text.Text.Contains("#docBuitenland#"))
                            {
                                text.Text = text.Text.Replace("#docBuitenland#", Parameters.Naam);
                                run.AppendChild(new Break());
                            }
                        }
                    }
                }

                mainPart.Document.Save();
                templateStream.Position = 0;
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    templateStream.CopyTo(memoryStream);
                    result = memoryStream.ToArray();
                }
            }

            byte[] fileContent = templateStream.ToArray();
            templateStream.Close();


            // Response.Buffer = true;
            Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            Response.AddHeader("Content-Disposition", "filename=document.docx");
            Response.BinaryWrite(fileContent);
            Response.End();
        }

    }

If you need to replace any text, you could try regex as per MSDN sample

using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
   docText = sr.ReadToEnd();
}

Regex regexText = new Regex("Hello world!");
docText = regexText.Replace(docText, "Hi Everyone!");

To replace in particular container such as table, you would need to enumerate tables and cells (in the same way as you do for paragraphs)

var tables = mainPart.Document.Descendants<Table>().ToList();
foreach (Table t in tables)
{
    var rows = t.Elements<TableRow>();
    foreach (TableRow row in rows)
    {
        var cells = row.Elements<TableCell>();
        foreach (TableCell cell in cells) 
            ...
    }
}

See MSDN for more details.

This makes the document incorrect to open =>

                var tables = mainPart.Document.Descendants<DocumentFormat.OpenXml.Wordprocessing.Table>().ToList();

                foreach (DocumentFormat.OpenXml.Wordprocessing.Table t in tables)
                {
                    var rows = t.Elements<DocumentFormat.OpenXml.Wordprocessing.TableRow>();
                    foreach (DocumentFormat.OpenXml.Wordprocessing.TableRow row in rows)
                    {
                        var cells = row.Elements<DocumentFormat.OpenXml.Wordprocessing.TableCell>();
                        foreach (DocumentFormat.OpenXml.Wordprocessing.TableCell cell in cells)
                        {
                            if (cell.InnerText.Contains("#bNaam#"))
                            {



                                //paragraph.InnerText will be empty
                                Run newRun = new Run();
                                newRun.AppendChild(new Text(cell.InnerText.Replace("#bNaam#", Parameters.Naam)));
                                //remove any child runs
                                cell.RemoveAllChildren<Run>();
                                //add the newly created run
                                cell.AppendChild(newRun);
                            }

                        }                          

                    }

                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM