C# 添加Word表格行或列
此经验内容将分享在C#程序中,给Word表格添加行或者列的方法。
工具/原料
Free Spire.Doc for .NET (免费版)
Visual Studio
dll文件获取及引用:
1、方法1:通过eiceblue官网获取dll文件包。下载后,解压文件。打开解压后的文件夹,安装程序。安装后,在程序中添加引用安装路径下bin文件夹中的Spire.Doc.dll文件。添加引用后如下图:
2、方法2:可通过Nuget下载。
【示例1】添加表格行
1、using Spire.Doc;namespace AddRow_Doc{ class Progr锾攒揉敫am { static void Main(string[] args) { //创建一个Document类对象,并加载Word文档 Document doc = new Document(); doc.LoadFromFile("test.docx"); //获取第一个table Table table = doc.Sections[0].Tables[0] as Spire.Doc.Table; //在指定位置新插入一行作为第三行 TableRow row = table.AddRow(); table.Rows.Insert(2, row); //在表格末尾添加一行 //table.AddRow(true, 4);//带格式添加 table.AddRow(false, 4);//不带格式添加 //保存文档 doc.SaveToFile("Result.docx", FileFormat.Docx2013); } }}
2、表格行添加效果:
【示例2】添加表格列
1、using Spire.Doc;namespace AddColumn{ class Progra罪焐芡拂m { static void Main(string[] args) { //加载文档 Document doc = new Document("Test.docx"); //获取第一节 Section section = doc.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; } //保存文档 doc.SaveToFile("AddColumn.docx", FileFormat.Docx2013); } }}
2、表格列添加效果: