簡體   English   中英

OpenXML SDK替換模板文檔中的文本

[英]OpenXML SDK replace text in Template Document

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

    }

如果您需要替換任何文本,則可以按照MSDN示例嘗試正則表達式

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

這使文檔無法正確打開=>

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

                        }                          

                    }

                }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM