您的位置:首页 > 编程语言 > ASP

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

2017-10-10 10:17 543 查看
1.今天介绍下第四种word模板写入数据,如图:



2.上图就是今天的模板,接下来就是填充数据了(此方法通用,比 builder.MoveToCell(0, 14 + i, 1, 0);这类方法好)

        #region 对表格进行修改

        private static Table EditCell(Table table, Document doc, int row, int cell, string value)

        {

            Aspose.Words.Tables.Cell c = table.Rows[row].Cells[cell];

            Paragraph p = new Paragraph(doc);

            p.AppendChild(new Run(doc, value));

            p.ParagraphFormat.Style.Font.Size = 8;    //设置字体大小

            p.ParagraphFormat.Style.Font.Name = "宋体";           //设置字体格式

            c.FirstParagraph.Remove();

            c.AppendChild(p);

            table.Rows[row].Cells[cell].Remove();

            table.Rows[row].Cells.Insert(cell, c);

            return table;

        }

        #endregion

3.就是调用2的方法进行填充数据

            string tempFile = Path.GetFullPath("resource/templete/项目建议书模板.doc").ToString();  //这个是word模板路径

            Document doc = new Document(tempFile);

            DocumentBuilder builder = new DocumentBuilder(doc);

            NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //获取word模板中所有表格table

            Aspose.Words.Tables.Table table4 = allTables[5] as Aspose.Words.Tables.Table;//拿到第6个表格                 

            for (int i = 0; i < dt3.Rows.Count; i++)    dt3为数据源DataTable

            {

                EditCell(table4, doc, 0, 1, "\n" + "设备类型:" + dt3.Rows[i]["SBLeiXing"].ToString() + "\r\n" +

                                         "设备名称:" + dt3.Rows[i]["SBMingCheng"].ToString() + "\r\n" +

                                         "设备数量:" + dt3.Rows[i]["ShuLiang"].ToString() + "\r\n");

                EditCell(table4, doc, 1, 1, dt3.Rows[i]["SBYunXingQK"].ToString());

                EditCell(table4, doc, 2, 1, dt3.Rows[i]["SBZTJXPingJiaJG"].ToString());

                EditCell(table4, doc, 3, 2, dt3.Rows[i]["AnQuanPingJia"].ToString());

                EditCell(table4, doc, 4, 2, dt3.Rows[i]["XiaoNengPingJia"].ToString());

                EditCell(table4, doc, 5, 2, dt3.Rows[i]["ZhouQiCBPingJia"].ToString());

             }

           doc.Save(filePath); //保存路径       filePath你可以写死,比如D:\\

4.填充数据结果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: