通过添加bookmark书签来添加数据,首先通过方法MoverToBookmark移动指定的标签位置,然后添加数据,添加完成后清除掉bookmark标示。

            string templateFile = Server.MapPath("User_tmplt.doc");
            string savePath = Server.MapPath("User.doc");

            Aspose.Words.Document doc = new Aspose.Words.Document(templateFile);
            Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);

            //表数据
            DataTable nameList = new DataTable();
            nameList.Columns.Add("编号");
            nameList.Columns.Add("姓名");
            nameList.Columns.Add("时间");
            DataRow row = null;
            for (int i = 0; i < 3; i++)
            {
                row = nameList.NewRow();
                row["编号"] = i.ToString().PadLeft(4, '0');
                row["姓名"] = "菜鸟程序员 " + i.ToString();
                row["时间"] = DateTime.Now.ToString();
                nameList.Rows.Add(row);
            }

            //获取表头的单元格的宽度
            List<double> widthList = new List<double>();
            for (int i = 0; i < nameList.Columns.Count; i++)
            {
                builder.MoveToCell(0, 0, i, 0); //移动单元格
                double width = builder.CellFormat.Width;//获取单元格宽度
                widthList.Add(width);
            }

            builder.MoveToBookmark("table");        //开始添加值
            for (var i = 0; i < nameList.Rows.Count; i++)
            {
                for (var j = 0; j < nameList.Columns.Count; j++)
                {
                    builder.InsertCell();// 添加一个单元格                    
                    builder.CellFormat.Borders.LineStyle = LineStyle.Single;
                    builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
                    builder.CellFormat.Width = widthList[j];
                    builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                    builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中对齐
                    builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                    builder.Write(nameList.Rows[i][j].ToString());
                }
                builder.EndRow();
            }
            doc.Range.Bookmarks["table"].Text = "";    // 清掉标示  

            doc.Save(savePath);

  

 

posted on 2018-08-09 10:38  itprobie-菜鸟程序员  阅读(1229)  评论(0编辑  收藏  举报