OpenXML SDK替换模板文档中的文本

时间:2015-03-18 10:55:31

标签: c# asp.net openxml openxml-sdk

使用OpenXML SDK,我创建了一个docx文件,我将其用作模板。它需要替换文档中的单词。好吧,如果我使用带有段落的文档,它是有效的。但是对于tablecell内的文本以及像break这样的段落中的文本它不起作用。在我的代码下面=>

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

    }

2 个答案:

答案 0 :(得分:0)

如果您需要替换任何文字,可以按照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!");

要替换特定容器(如表),您需要枚举表格和单元格(与您对段落的方式相同)

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) 
            ...
    }
}

有关详细信息,请参阅MSDN

答案 1 :(得分:0)

这使得文档不正确打开=&gt;

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

                        }                          

                    }

                }