【问题标题】:OpenXML SDK replace text in Template DocumentOpenXML SDK 替换模板文档中的文本
【发布时间】:2015-03-18 10:55:30
【问题描述】:

使用 OpenXML SDK,我创建了一个 docx 文件,我将其用作模板。它需要替换文档中的单词。好吧,如果我使用带有段落的文档,它就可以工作。但是对于表格单元格中的文本和段落中的文本(如中断),它不起作用。在我的代码下面=>

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

    }

【问题讨论】:

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


【解决方案1】:

如果您需要替换任何文本,您可以按照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

【讨论】:

    【解决方案2】:

    这会使文档无法打开 =>

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多