Aspose.Words模板创建Word【二】

摘要:
本篇内容主要介绍通过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); //将此行插入第一行的上方 
        }
        #endregion
        doc.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文档生成表格添加的数据情况。
这里写图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值