轉帖|使用教程|編輯:黃竹雯|2018-12-28 13:55:56.000|閱讀 2234 次
概述:Spire.Doc系列教程之根據分節符和分頁符拆分 Word 文檔
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
在Word文檔中,我們可以通過最簡單的方法來拆分Word文檔,那就是打開一個是需要拆分的文檔的副本,刪除我們不需要的內容然后將剩余內容保存為新文檔到本地。雖然操作簡單,但是一節一節的刪除是個相當繁瑣且枯燥的過程。利用Spire.Doc,我們可以程序化的根據分節符和分頁符來拆分Word文檔,這避免了手動冗雜的操作。本文將對此做詳細介紹。
//實例化Document對象 Document document = new Document(); //載入待拆分的Word文檔 document.LoadFromFile(@"測試文檔.docx"); Document newWord; for (int i = 0; i < document.Sections.Count; i++) { //每有一個section就創建一個新的文檔 newWord = new Document(); //復制section內容到新文檔 newWord.Sections.Add(document.Sections[i].Clone()); //保存文檔 newWord.SaveToFile(String.Format(@"拆分結果\分節符拆分的結果文檔_{0}.docx", i)); }
//實例化Document對象 Document original = new Document(); //載入待拆分的Word文檔 original.LoadFromFile(@"C:\Users\Administrator\Desktop\template.docx"); //實例化一個新的文檔并添加新章節 Document newWord = new Document(); Section section = newWord.AddSection(); int index = 0; //根據章節,段落的層次由大到小依次遍歷文檔元素,復制內容到新的文檔 foreach (Section sec in original.Sections) { foreach (DocumentObject obj in sec.Body.ChildObjects) { if (obj is Paragraph) { Paragraph para = obj as Paragraph; section.Body.ChildObjects.Add(para.Clone()); foreach (DocumentObject parobj in para.ChildObjects) { //找到段落中的分頁符,保存到新文檔 if (parobj is Break && (parobj as Break).BreakType == BreakType.PageBreak) { int i = para.ChildObjects.IndexOf(parobj); section.Body.LastParagraph.ChildObjects.RemoveAt(i); newWord.SaveToFile(String.Format(@"C:\Users\Administrator\Desktop\拆分結果\分頁符拆分的結果文檔_{0}.docx", index), FileFormat.Docx); index++; //一個文檔完成之后新建一個文檔 newWord = new Document(); section = newWord.AddSection(); //復制上一個分頁符所在的段落的所有內容到新文檔 section.Body.ChildObjects.Add(para.Clone()); //如果新文檔第一段(也就是剛剛復制的那一段)沒有子元素, //則把文檔的第一個子元素刪除 if (section.Paragraphs[0].ChildObjects.Count == 0) { section.Body.ChildObjects.RemoveAt(0); } else { //如果有內容則刪除分頁符之前的所有內容 while (i >= 0) { section.Paragraphs[0].ChildObjects.RemoveAt(i); i--; } } } } } if (obj is Table) { section.Body.ChildObjects.Add(obj.Clone()); } } } newWord.SaveToFile(String.Format(@"C:\Users\Administrator\Desktop\拆分結果\分頁符拆分的結果文檔_{0}.docx", index), FileFormat.Docx);
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn