摘要:
本篇内容主要介绍通过Aspose.Words插件动态操作表格,批量添加行数据。
说明:
第一步:制作模板word。
第二步:代码实现填充表格行记录。
class Program
{static void Main(string[] args){string templatePath = @"C:\Users\JeterJing\Desktop\Aspose.Words\template\template.docx";string targetPath = @"C:\Users\JeterJing\Desktop\Aspose.Words\create-example\" + Guid.NewGuid().ToString() + ".docx";string message = string.Empty;FillContentByTable(templatePath,targetPath,ref message); Console.WriteLine("创建成功!请按照任意键结束。");Console.ReadKey(true);}public static void FillContentByTable(string templatePath, string targetPath, ref string msg){Document doc = new Document(templatePath);DocumentBuilder builder = new DocumentBuilder(doc);//获取表格节点集合NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);#region 动态添加表格中的数据//拿到word文档中的表格:根据word文档中表格索引定位表格Table table = tables[1] as Table;for (int i = 0; i < 3; i++){var row = CreateRow(5, new[] { "A001", "专业技术资质", "已审核", "已审核", DateTime.Now.ToString("yyyy-MM-dd") }, doc);table.Rows.Insert(2, row); //将此行插入第一行的上方 }#endregiondoc.Save(targetPath, SaveFormat.Docx);}public static Row CreateRow(int columnCount, string[] columnValues, Document doc){Row r = new Row(doc);for (int i = 0; i < columnCount; i++){if (columnValues.Length > i){var cell = CreateCell(columnValues[i], doc);r.Cells.Add(cell);}else{var cell = CreateCell("", doc);r.Cells.Add(cell);}}return r;}public static Cell CreateCell(string value, Document doc){Cell c = new Cell(doc);Paragraph p = new Paragraph(doc);p.AppendChild(new Run(doc, value));c.AppendChild(p);return c;}
}
第三步:查看运行结果。
再查看一下word文档生成表格添加的数据情况。