对于word操做通常是对已有word模板的操做,直接新建的不考虑,网上教程不少,本身看吧 通常有如下几种办法(忘了具体几种了,通常状况下如下就够了) 一、经过书签替换 顾名思义,就是先定义一个书签,而后在书签的位置填进去相应的数据或图片,具体操做 1 >先在word上插入->书签->定义书签名 2 >在程序中使用ui
Document doc = new Document(tmppath); //载入模板 Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc); builder.MoveToBookmark("zy");//跳转到书签名是zy的位置 builder.Write("书签位置要替换的文字");
图片还有一个根据位置定位到某个位置而后粘贴,实例以下code
builder.InsertImage(img, RelativeHorizontalPosition.Page, left, RelativeVerticalPosition.TopMargin, 0, width, height, WrapType.None);
参数具体含义有很明了,就不说了。 二、经过表格单元格替换 通常word模板里边基本就是表格,因此对表格的操做很重要 先找到相应的表格orm
Document doc = new Document(tmppath); //载入模板 Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc); NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); Table table = allTables[0] as Aspose.Words.Tables.Table;//拿到第一个表格
而后对表格进行操做,可是默认的表格的单元格是只可读的,因而我想出一个办法,就是先取到单元格A存储到一个新建的单元格对象单元格B里面,而后修改单元格B,最后删除单元格A而且把单元格B添加到单元格A中,这样就完美的替换了单元格了,并且原来单元格的宽高都不用在调整了,因而我把它封装成了一个方法示例以下对象
/// <summary> /// 修改表中的数据 /// </summary> /// <param name="table">表名</param> /// <param name="doc">文档</param> /// <param name="row">要修改行</param> /// <param name="cell">要修改列</param> /// <param name="value">修改后的值</param> private static Table EditCell(Table table, Document doc, int row, int cell, string value) { Cell c = table.Rows[row].Cells[cell]; Paragraph p = new Paragraph(doc); p.AppendChild(new Run(doc, value)); p.ParagraphFormat.Style.Font.Size = 10; 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; }
3 >就是删除原来的单元格而后再添加一个新建的单元格,而后自定义属性(宽高等) 这个不推荐,只是原来没有想好2方法的替代品,是老版本,可是仍是显示一下吧,记念本身的努力 方法以下教程
private static Aspose.Words.Tables.Cell CreateCell(string value, Document doc, double cellwidth) { Aspose.Words.Tables.Cell c1 = new Aspose.Words.Tables.Cell(doc); c1.CellFormat.Width = cellwidth; c1.CellFormat.Borders.LineStyle = LineStyle.Single; //c1.CellFormat.WrapText = false; Aspose.Words.Paragraph p = new Paragraph(doc); p.AppendChild(new Run(doc, value)); //Table table = new Table(doc); //p.AppendChild(table); p.ParagraphFormat.Style.Font.Size = 10; p.ParagraphFormat.Style.Font.Name = "华文楷体"; c1.AppendChild(p); return c1; }
4 >添加数据到单元格,只适用于表格,非常推荐,很好用,具体就是直接向某个表格的某一行的某一列添加值,示例以下:图片
builder.MoveToCell(0, 31, 1, 0);//先跳转到第0个表格,第31行,第1列 builder.Write("要写入的数据");
注意:行和列都是从0开始的,不是从1开始的 5 >经过替换域名的方法 和书签的方法类似。文档