Spire.Doc不仅支持添加表格到Word文档,还支持对表格进行多种操作,如设置边框,添加图片,合并和拆分单元格等。本文将介绍如何使用Spire.Doc对Word文档中表格的单元格进行合并与拆分操作。
合并单元格
在Spire.Doc中,合并单元格分为水平合并和垂直合并两种。在水平合并时,需要指定行,合并的起始单元格和结束单元格。在垂直合并时,需要指定列,合并的起始行和结束行。
C#
//新建Word文档
Document document = new Document();
//添加section
Section section = document.AddSection();
//添加一个4 x 4的表格到section
Table table = section.AddTable(true);
table.ResetCells(4, 4);
//水平合并(合并第1行的第1、2、3、4个单元格)
table.ApplyHorizontalMerge(0, 0, 3);
//垂直合并(合并第1列的第3、4个单元格)
table.ApplyVerticalMerge(0, 2, 3);
//保存文档
document.SaveToFile("合并.docx", FileFormat.Docx);
VB.NET
'新建Word文档
Dim document As Document = New Document
'添加section
Dim section As Section = document.AddSection
'添加一个4 x 4的表格到section
Dim table As Table = section.AddTable(true)
table.ResetCells(4, 4)
'水平合并(合并第1行的第1、2、3、4个单元格)
table.ApplyHorizontalMerge(0, 0, 3)
'垂直合并(合并第1列的第3、4个单元格)
table.ApplyVerticalMerge(0, 2, 3)
'保存文档
document.SaveToFile("合并.docx", FileFormat.Docx)
拆分单元格
拆分单元格时,需要先获取单元格,然后指定单元格拆分的列数和行数。
C#
//新建Word文档
Document document = new Document();
//添加section
Section section = document.AddSection();
//添加一个4 x 4的表格到section
Table table = section.AddTable(true);
table.ResetCells(4, 4);
//将第4行的第4个单元格拆分为3列2行
table.Rows[3].Cells[3].SplitCell(3, 2);
//保存文档
document.SaveToFile("拆分.docx", FileFormat.Docx);
VB.NET
'新建Word文档
Dim document As Document = New Document
'添加section
Dim section As Section = document.AddSection
'添加一个4 x 4的表格到section
Dim table As Table = section.AddTable(true)
table.ResetCells(4, 4)
'将第4行的第4个单元格拆分为3列2行
table.Rows(3).Cells(3).SplitCell(3, 2)
'保存文档
document.SaveToFile("拆分.docx", FileFormat.Docx)