且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 OpenXML SDK 用换行符(换行符)替换 docx 文件上的文本

更新时间:2023-02-19 16:25:02

尝试使用 打破.检查此链接上的示例.你只需要附加一个 Break

Try with a break. Check the example on this link. You just have to append a Break

段落、智能标签、超链接都在运行.所以也许你可以试试这个方法.要更改表格内的文本,您必须使用此 方法.同样,文本始终在 Run 内.

Paragraphs, smart tags, hyperlinks are all inside Run. So maybe you could try this approach. To change the text inside a table, you will have to use this approach. Again the text is always inside a Run.

如果你说替换只是替换一个空字符串,我会试试这个:

If you are saying that the replace is only replacing for an empty string, i would try this:

using (WordprocessingDocument doc =
                WordprocessingDocument.Open(@"yourpath	estdocument.docx", true))
        {
            var body = doc.MainDocumentPart.Document.Body;
            var paras = body.Elements<Paragraph>();

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