private static void ModifyWordParagraphTextContent(OXW.Paragraph paragraph, string txt) { if (null != paragraph) { OXW.Run run = paragraph.Descendants <OXW.Run>().FirstOrDefault(); if (null != run) { run = run.CloneNode(true) as OXW.Run; paragraph.RemoveAllChildren <OXW.Run>(); } else { run = new OXW.Run(); } OXW.Text text = run.Descendants <OXW.Text>().FirstOrDefault(); text = (null == text ? new OXW.Text() : text.CloneNode(true) as OXW.Text); run.RemoveAllChildren <OXW.Text>(); text.Text = txt; if (!string.IsNullOrEmpty(txt) && (char.IsWhiteSpace(txt[0]) || char.IsWhiteSpace(txt[txt.Length - 1]))) { text.Space = SpaceProcessingModeValues.Preserve; } run.Append(text); paragraph.Append(run); } }
public void ReplaceString(OpenXmlElement element, string val) { var text = element.Descendants <Word.Text>().FirstOrDefault(); var run = text == null?element.Descendants <Word.Run>().FirstOrDefault() : FindParent <Word.Run>(text); var runp = run.Parent; var paragraph = FindParent <Word.Paragraph>(runp); run.RsidRunProperties = null; run.RemoveAllChildren <Word.Text>(); run.RemoveAllChildren <Word.RunProperties>(); runp.RemoveAllChildren <Word.Run>(); runp.RemoveAllChildren <Word.Break>(); if (paragraph.ParagraphProperties?.ParagraphMarkRunProperties != null) { run.RunProperties = new Word.RunProperties(); foreach (var item in paragraph.ParagraphProperties.ParagraphMarkRunProperties) { run.RunProperties.AppendChild(item.CloneNode(true)); } } if (text == null) { text = new Word.Text(); } else if (text.Parent != null) { text.Remove(); } string[] pagesplit = val.TrimEnd("\r\n".ToCharArray()).Split("\f".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); for (int p = 0; p < pagesplit.Length; p++) { var lineSpit = pagesplit[p].Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); if (lineSpit.Length > 0) { for (int i = 0; i < lineSpit.Length; i++) { if (p == 0 && i == 0) { text.Text = lineSpit[0]; text.Space = SpaceProcessingModeValues.Preserve; run.Append(text); runp.Append(run); continue; } Word.Run r = run.Clone() as Word.Run; r.RemoveAllChildren <Word.Text>(); r.Append(new Word.Text(lineSpit[i]) { Space = SpaceProcessingModeValues.Preserve }); Word.Paragraph pr = (Word.Paragraph)paragraph.Clone(); pr.RemoveAllChildren <Word.Run>(); pr.RemoveAllChildren <Word.Break>(); pr.RemoveAllChildren <Word.SdtBlock>(); pr.RemoveAllChildren <Word.SdtRun>(); pr.Append(r); paragraph.Parent.InsertAfter <Word.Paragraph>(pr, paragraph); paragraph = pr; } } if (p < pagesplit.Length - 1) { var bp = new Word.Break() { Type = Word.BreakValues.Page }; paragraph.AppendChild(bp); } } }