本文将介绍通过Spire.Doc for .NET来复制Word表格中的行或者列的方法。
复制表格行
C#
using Spire.Doc;
namespace CopyRow
{
class Program
{
static void Main(string[] args)
{
//加载测试文档
Document doc = new Document();
doc.LoadFromFile("sample.docx");
//获取表格
Section sec = doc.Sections[0];
Table table = sec.Tables[0] as Spire.Doc.Table;
//获取第三行,并复制
TableRow row = table.Rows[2].Clone();
//将复制后的行作为第四行插入到表格
table.Rows.Insert(3, row);
//table.Rows.Add(row);//默认将复制后的行添加在表格最下方
//保存文档
doc.SaveToFile("CopyRow.docx",FileFormat.Docx2013);
}
}
}
VB.NET
Imports Spire.Doc
Namespace CopyRow
Class Program
Private Shared Sub Main(ByVal args() As String)
'加载测试文档 Dim doc As Document = New Document doc.LoadFromFile("sample.docx") '获取表格
Dim sec As Section = doc.Sections(0)
Dim table As Table = CType(sec.Tables(0),Spire.Doc.Table)
'获取第三行,并复制 Dim row As TableRow = table.Rows(2).Clone '将复制后的行作为第四行插入到表格
table.Rows.Insert(3, row)
'table.Rows.Add(row);'默认将复制后的行添加在表格最下方
'保存文档 doc.SaveToFile("CopyRow.docx",FileFormat.Docx2013) End Sub End Class End Namespace
表格行复制效果:
复制表格列
C#
using Spire.Doc;namespace CopyColumn{class Program{static void Main(string[] args){//加载测试文档 Document doc = new Document();doc.LoadFromFile("sample.docx");//获取表格 Section section = doc.Sections[0];Table table = section.Tables[0]as Spire.Doc.Table;//遍历表格每一行 for (int i = 0;i < table.Rows.Count;i++){TableRow row = table.Rows[i];//获取每一行 TableCell cell = (TableCell)row.Cells[1].Clone();//获取每行中的第2个单元格,并复制 row.Cells.Add(cell);//默认在表格最后一列添加复制后的单元格 // row.Cells.Insert(3,cell);//在指定位置插入一列复制后的单元格}//保存文档 doc.SaveToFile("CopyColumn.docx",FileFormat.Docx2013);}}}
VB.NET
Imports Spire.Doc Namespace CopyColumn Class Program Private Shared Sub Main(ByVal args() As String) '加载测试文档
Dim doc As Document = New Document
doc.LoadFromFile("sample.docx")
'获取表格 Dim section As Section = doc.Sections(0) Dim table As Table = CType(section.Tables(0),Spire.Doc.Table) '遍历表格每一行
Dim i As Integer = 0
Do While (i < table.Rows.Count)
Dim row As TableRow = table.Rows(i) '获取每一行 Dim cell As TableCell = CType(row.Cells(1).Clone,TableCell)'获取每行中的第2个单元格,并复制
row.Cells.Add(cell)'默认在表格最后一列添加复制后的单元格 ' row.Cells.Insert(3, cell); ' 在指定位置插入一列复制后的单元格 i = (i + 1) Loop '保存文档
doc.SaveToFile("CopyColumn.docx", FileFormat.Docx2013)
End Sub
End Class
End Namespace
表格列复制效果: