文檔金喜正規買球>>E-iceblue中文文檔>>防止Word 出現分頁符
防止Word 出現分頁符
我們經常在頁面底部附近開始一個表格。如果單行或多行太長而無法容納在頁面的上邊距和下邊距之間,Microsoft Word 會自動在表格中放置分頁符。因此,我們寧愿將同一行放在一頁上,或者將整個表格放在下一頁上,而不是分成兩頁。在本文中,我將向您介紹兩種通過 Spire.Doc 避免 Word 表格中出現分頁符的方法。
假設我們有一個這樣的 Word 表格(第 2 行拆分到不同的頁面),我們可能希望通過以下兩種方法來優化布局。
技術交流Q群(767755948)
方法1:將整個表格保持在同一頁面上。
第 1 步:創建一個新的 Word 文檔并加載測試文件。
Document doc = new Document("Test.docx");
第 2 步:從 Word 文檔中獲取表格。
Table table = doc.Sections[0].Tables[0] as Table;
第 3 步:更改段落設置以使它們保持在一起。
foreach (TableRow row in table.Rows) { foreach (TableCell cell in row.Cells) { foreach (Paragraph p in cell.Paragraphs) { p.Format.KeepFollow = true; } } }
第 4 步:保存并啟動文件。
doc.SaveToFile("Result.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("Result.docx");
輸出:
方法 2: 防止 Word 在兩頁之間斷開表格行。
仍然存在表格不夠小到不能放在一頁上的情況,您可以防止 Word 破壞包含跨兩頁的多個段落的表格行。在這個例子中,第二行已經被分成不同的頁面,我們可以用下面的語句設置TableFormat的屬性來避免這個問題。
table.TableFormat.IsBreakAcrossPages = false;用這句話代替第三步,你會得到如下布局:
完整的 C# 代碼:
方法一
using Spire.Doc; using Spire.Doc.Documents; namespace PreventPageBreak { class Program { static void Main(string[] args) { Document doc = new Document("Test.docx"); Table table = doc.Sections[0].Tables[0] as Table; foreach (TableRow row in table.Rows) { foreach (TableCell cell in row.Cells) { foreach (Paragraph p in cell.Paragraphs) { p.Format.KeepFollow = true; } } } doc.SaveToFile("Result.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("Result.docx"); } } }
方法二
using Spire.Doc; using Spire.Doc.Documents; namespace PreventPageBreak { class Program { static void Main(string[] args) { Document doc = new Document("Test.docx"); Table table = doc.Sections[0].Tables[0] as Table; table.TableFormat.IsBreakAcrossPages = false; doc.SaveToFile("Result.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("Result.docx"); } } }