本文将介绍如何使用Spire.Doc对现有Word表格进行: 添加行和列,删除行和列,以及设置行高和列宽操作。
原表格截图如下:
添加行和列
添加和插入行
C#
//载入文档
Document document = new Document("Table.docx");
//获取第一个节
Section section = document.Sections[0];
//获取第一个表格
Table table = section.Tables[0] as Table;
//添加一行到表格的最后
table.AddRow(true, 4);
//插入一行到表格的第三行
table.Rows.Insert(2, table.AddRow());
//保存文档
document.SaveToFile("AddRow.docx", FileFormat.Docx2013);
VB.NET
'载入文档
Dim document As Document = New Document("Table.docx")
'获取第一个节
Dim section As Section = document.Sections(0)
'获取第一个表格
Dim table As Table = CType(section.Tables(0),Table)
'添加一行到表格的最后
table.AddRow(true, 4)
'插入一行到表格的第三行
table.Rows.Insert(2, table.AddRow)
'保存文档
document.SaveToFile("AddRow.docx", FileFormat.Docx2013)
添加列
C#
//载入文档
Document document = new Document("Table.docx");
//获取第一个节
Section section = document.Sections[0];
//获取第一个表格
Table table = section.Tables[0] as Table;
//添加一列到表格,设置单元格的宽度和宽度类型
for (int i = 0; i < table.Rows.Count; i++)
{
TableCell cell = table.Rows[i].AddCell(true);
cell.Width = table[0, 0].Width;
cell.CellWidthType = table[0, 0].CellWidthType;
}
//保存文档
document.SaveToFile("AddColumn.docx", FileFormat.Docx2013);
VB.NET
'载入文档
Dim document As Document = New Document("Table.docx")
'获取第一个节
Dim section As Section = document.Sections(0)
'获取第一个表格
Dim table As Table = CType(section.Tables(0),Table)
'添加一列到表格,设置单元格的宽度和宽度类型
Dim i As Integer = 0
Do While (i < table.Rows.Count)
Dim cell As TableCell = table.Rows(i).AddCell(true)
cell.Width = table(0, 0).Width
cell.CellWidthType = table(0, 0).CellWidthType
i = (i + 1)
Loop
'保存文档
document.SaveToFile("AddColumn.docx", FileFormat.Docx2013)
删除行和列
C#
//载入文档
Document doc = new Document("Table.docx");
//获取第一个表格
Table table = doc.Sections[0].Tables[0] as Table;
//删除第二行
table.Rows.RemoveAt(1);
//删除第二列
for (int i = 0; i < table.Rows.Count; i++)
{
table.Rows[i].Cells.RemoveAt(1);
}
//保存文档
doc.SaveToFile("RemoveRowAndColumn.docx", FileFormat.Docx2013);
VB.NET
'载入文档
Dim doc As Document = New Document("Table.docx")
'获取第一个表格
Dim table As Table = CType(doc.Sections(0).Tables(0),Table)
'删除第二行
table.Rows.RemoveAt(1)
'删除第二列
Dim i As Integer = 0
Do While (i < table.Rows.Count)
table.Rows(i).Cells.RemoveAt(1)
i = (i + 1)
Loop
'保存文档
doc.SaveToFile("RemoveRowAndColumn.docx", FileFormat.Docx2013)
设置行高和列宽
C#
//载入文档
Document document = new Document("Table.docx");
//获取第一个表格
Table table = document.Sections[0].Tables[0] as Table;
//设置第一行的行高
table.Rows[0].Height = 40;
for (int i = 0; i < table.Rows.Count; i++)
{
//设置第二列的列宽
table.Rows[i].Cells[1].Width = 40;
}
//保存文档
document.SaveToFile("SetRowHeightAndColumnWidth.docx", FileFormat.Docx2013);
VB.NET
'载入文档
Dim document As Document = New Document("Table.docx")
'获取第一个表格
Dim table As Table = CType(document.Sections(0).Tables(0),Table)
'设置第一行的行高
table.Rows(0).Height = 40
Dim i As Integer = 0
Do While (i < table.Rows.Count)
'设置第二列的列宽
table.Rows(i).Cells(1).Width = 40
i = (i + 1)
Loop
'保存文档
document.SaveToFile("SetRowHeightAndColumnWidth.docx", FileFormat.Docx2013)