【问题标题】:Remove empty paragraphs from .docx using OpenXML SDK 2.0使用 OpenXML SDK 2.0 从 .docx 中删除空段落
【发布时间】:2011-11-11 13:29:49
【问题描述】:

我试图在将内容解析为 xml 之前从 .docx 文件中删除空段落。我将如何实现这一目标?

Protected Sub removeEmptyParagraphs(ByRef body As DocumentFormat.OpenXml.Wordprocessing.Body)
    Dim colP As IEnumerable(Of Paragraph) = body.Descendants(Of Paragraph)()

    Dim count As Integer = colP.Count
    For Each p As Paragraph In colP
        If (p.InnerText.Trim() = String.Empty) Then
            body.RemoveChild(Of Paragraph)(p)
        End If
    Next
End Sub

【问题讨论】:

    标签: vb.net openxml-sdk


    【解决方案1】:

    您可能遇到的问题是从每个块的列表中删除项目。您可以尝试使用 linq 和 RemoveAll 方法:

    Protected Sub removeEmptyParagraphs(ByRef body As DocumentFormat.OpenXml.Wordprocessing.Body)
        Dim colP As IEnumerable(Of Paragraph) = body.Descendants(Of Paragraph)()
        colP.RemoveAll(Function(para) para.InnerText.Trim() = String.Empty)
    End Sub
    

    【讨论】:

      【解决方案2】:

      这将有助于删除段落甚至空白页的空白。

      IEnumerable<Paragraph> paragraphs =       
                           myDoc.MainDocumentPart.Document.Body.Elements<Paragraph>();
      
                  foreach (Paragraph paragraph in paragraphs)
                  {
                      if (paragraph != null && string.IsNullOrWhiteSpace(paragraph.InnerText))
                      {
                          paragraph.ParagraphProperties = new ParagraphProperties(
                                            new ParagraphStyleId() { Val = "No Spacing" },
                                            new SpacingBetweenLines() { After = "0" }
                                            );
                          paragraph.ParagraphProperties.SpacingBetweenLines.AfterLines = 0;
                          paragraph.ParagraphProperties.SpacingBetweenLines.BeforeLines = 0;
                          paragraph.ParagraphProperties.SpacingBetweenLines.Line = "0";
      
                      }
                  }
      

      【讨论】:

      • 编辑您的答案以包含 VB.NET 版本可能很有用,尤其是当问题被标记为 VB.NET 时。
      猜你喜欢
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多