C# Aspose.Word 操作word文档【三】

第三种方法我也是从网上找到的,借鉴下了,然后自己整理出的!

1、建好word 模板



你没有看错,第三种是只有这样的表头,然后动态生成数据!


2、网上找到的代码:

       static Aspose.Words.Tables.Cell CreateCell(string value, Document doc)
        {
            
            Aspose.Words.Tables.Cell c1 = new Aspose.Words.Tables.Cell(doc);
            Aspose.Words.Paragraph p = new Paragraph(doc);
            p.AppendChild(new Run(doc, value));
            c1.AppendChild(p);
            return c1;
        }

      static Aspose.Words.Tables.Row CreateRow(int columnCount, string[] columnValues, Document doc)
        {
            Aspose.Words.Tables.Row r2 = new Aspose.Words.Tables.Row(doc);
            for (int i = 0; i < columnCount; i++)
            {
                if (columnValues.Length > i)
                {
                    var cell = CreateCell(columnValues[i], doc);
                    r2.Cells.Add(cell);
                }
                else
                {
                    var cell = CreateCell("", doc);
                    r2.Cells.Add(cell);
                }

            }
            return r2;
        }


3、调用网上的代码,结合自己代码:

            string tempFile = Path.GetFullPath("resource/templete/项目建议书模板.doc").ToString();
            Document doc = new Document(tempFile);
            DocumentBuilder builder = new DocumentBuilder(doc);
            NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //获取word中所有表格table

            Aspose.Words.Tables.Table table = allTables[4] as Aspose.Words.Tables.Table;//拿到第5个表格          这里你word中是第几个表格就写第几个表格
            for (int i = 0; i < dt3.Rows.Count; i++)   //dt3  为数据源
            {            

                var row = CreateRow(13, (new string[] { (dt3.Rows.Count-i).ToString(), dt3.Rows[i]["SBBianHao"].ToString(), dt3.Rows[i]["ZiChanBianHao"].ToString(), dt3.Rows[i]["SBMingCheng"].ToString(),dt3.Rows[i]["SuoShuZhanXian"].ToString()
                ,dt3.Rows[i]["SBLeiXing"].ToString(),dt3.Rows[i]["DianYaDengJi"].ToString(),dt3.Rows[i]["SBXingHao"].ToString(),dt3.Rows[i]["TouYunRiQi"].ToString(),dt3.Rows[i]["ShuLiang"].ToString(),
                dt3.Rows[i]["JiLiangDanWei"].ToString(),dt3.Rows[i]["ChuZhiJianYi"].ToString(),dt3.Rows[i]["BeiZhu"].ToString()}), doc); //创建一行
                table.Rows.Insert(1, row); //将此行插入第一行的上方             
            }

4、效果图:



注意:下一篇介绍Aspose.Word 对word 中table 的复制,粘贴,且赋值。同样会使动态多条数据


  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专家-郭老师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值