在 Word 中,我们可以以最简单的方式拆分 Word 文档——打开原始文档的副本,删除不需要的部分,然后将剩余部分保存到本地驱动器。但是逐节做这个是相当麻烦和无聊的。本文将解释我们如何使用 Spire.Doc for .NET 以编程方式通过分节符将 Word 文档拆分为多个文档,而不是手动复制和删除。
Spire.Doc for.NET 最新下载
欢迎下载|体验更多E-iceblue产品 技术交流Q群(767755948)
详细步骤和代码片段:
第 1步:初始化一个新的word文档对象并加载包含两个部分的原始word文档。
Document document = new Document();
document.LoadFromFile("Test.docx");
第 2 步:定义另一个新的 word 文档对象。
Document newWord;
第 3 步:遍历原word文档的所有section,将每个section克隆并作为新的section添加到一个新的word文档中,然后将文档保存到指定路径。
for (int i = 0; i < document.Sections.Count; i++)
{
newWord = new Document();
newWord.Sections.Add(document.Sections[i].Clone());
newWord.SaveToFile(String.Format(@"test\out_{0}.docx", i));
}
运行项目,我们将得到以下输出:
完整代码:
using System;
using Spire.Doc;
namespace Split_Word_Document
{
class Program
{
static void Main(string[] args)
{
Document document = new Document();
document.LoadFromFile("Test.doc");
Document newWord;
for (int i = 0; i < document.Sections.Count; i++)
{
newWord = new Document();
newWord.Sections.Add(document.Sections[i].Clone());
newWord.SaveToFile(String.Format(@"test\out_{0}.docx", i));
}
}
}
}
更多推荐
Word控件Spire.Doc 【文档操作】教程(十):在 C# 中通过分节符将 Word 文档拆分为多个文档
发布评论