假设我们有一个这样的 Word 表格(第 2 行拆分到不同的页面),我们可能希望通过以下两种方法来优化布局。

方法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");}}}
欢迎下载|体验更多E-iceblue产品
获取更多信息请咨询在线客服 ;
标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!