C#自动删除Word文档空白行和空白页的完整代码
作者:用户835629078051
在处理 Word 文档时,经常会遇到空白行、空表格或空白页的问题,这不仅影响排版美观,还可能导致文档页数冗余,所以本文将介绍如何使用 Spire.Doc for .NET 在 C# 中自动删除 Word 文档的空白行、空表格和空白页,需要的朋友可以参考下
引言
在处理 Word 文档时,经常会遇到空白行、空表格或空白页的问题,这不仅影响排版美观,还可能导致文档页数冗余。手动逐一清理既麻烦又低效。本文将介绍如何使用 Spire.Doc for .NET 在 C# 中自动删除 Word 文档的空白行、空表格和空白页。
环境准备
在项目中引入 Spire.Doc for .NET 的最简便方式是通过 NuGet:
Install-Package Spire.Doc
安装完成后,在 C# 代码文件中引入命名空间:
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields;
删除空白行
Word 文档中的段落对象 (Paragraph
) 如果既没有文本,也没有其他元素,就可以视为空白行。我们只需遍历所有段落,将这些段落删除即可。
// 删除空白段落 for (int i = section.Paragraphs.Count - 1; i >= 0; i--) { Paragraph para = section.Paragraphs[i]; if (string.IsNullOrWhiteSpace(para.Text) && para.ChildObjects.Count == 0) { section.Paragraphs.Remove(para); } }
删除空表格
有时 Word 文档中会存在没有任何内容的表格,这些表格通常是误操作插入的,可以通过检查所有单元格是否为空来判断。
// 删除空表格 for (int t = section.Tables.Count - 1; t >= 0; t--) { Table table = section.Tables[t] as Table; bool isEmpty = true; foreach (TableRow row in table.Rows) { foreach (TableCell cell in row.Cells) { if (!string.IsNullOrWhiteSpace(cell.Paragraphs[0].Text)) { isEmpty = false; break; } } if (!isEmpty) break; } if (isEmpty) { section.Tables.Remove(table); } }
删除空白页
Word 中有时会保留空的节(Section),这些节往往会形成空白页。我们可以检测该节是否完全为空,并将其移除。
// 删除空白 Section(空白页) if (section.Paragraphs.Count == 0 && section.Tables.Count == 0) { document.Sections.Remove(section); }
完整示例代码
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace RemoveEmptyContent { class Program { static void Main(string[] args) { // 加载 Word 文档 Document document = new Document(); document.LoadFromFile("Sample.docx"); // 遍历所有节 for (int s = document.Sections.Count - 1; s >= 0; s--) { Section section = document.Sections[s]; // 删除空白行 for (int i = section.Paragraphs.Count - 1; i >= 0; i--) { Paragraph para = section.Paragraphs[i]; if (string.IsNullOrWhiteSpace(para.Text) && para.ChildObjects.Count == 0) { section.Paragraphs.Remove(para); } } // 删除空表格 for (int t = section.Tables.Count - 1; t >= 0; t--) { Table table = section.Tables[t] as Table; bool isEmpty = true; foreach (TableRow row in table.Rows) { foreach (TableCell cell in row.Cells) { if (!string.IsNullOrWhiteSpace(cell.Paragraphs[0].Text)) { isEmpty = false; break; } } if (!isEmpty) break; } if (isEmpty) { section.Tables.Remove(table); } } // 删除空白页 if (section.Paragraphs.Count == 0 && section.Tables.Count == 0) { document.Sections.Remove(section); } } // 保存结果 document.SaveToFile("Cleaned.docx", FileFormat.Docx); } } }
总结
本文介绍了如何使用 Spire.Doc for .NET 在 C# 中清理 Word 文档的冗余内容,包括 空白行、空表格和空白页。通过简单的几步操作,就能让文档变得更简洁、美观。
如果你还想进一步优化文档的排版,例如 只保留正文段落,自动去掉所有空内容后重新排版,也可以在此代码的基础上扩展。
到此这篇关于C#自动删除Word文档空白行和空白页的完整代码的文章就介绍到这了,更多相关C#自动删除Word空白行和空白页内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!