asp教程(超全!ASP.NET中使用Aspose.Words操作表格Table教程)

Aspose.Words是一款先进的类库,使您可以直接在各个应用程序中执行各种文档处理任务。Aspose.Words支持DOC,OOXML,RTF,HTML,OpenDocument, PDF, XPS, EPUB和其他格式。使用Aspose.Words,您可以生成,更改,转换,渲染和打印文档而不使用Microsoft Word。

一、创建Document

//根据模板创建文档,可为空 var filename = Server.MapPath("~/xls_template/doc.doc"); Aspose.Words.Document doc=new Aspose.Words.Document(filename); Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);

二、创建Table

  • 不使用模板:模板中没有表格时需要手动增加Table

//返回一个Apose.Words.Tables.Table对象 Apose.Words.Tables.Table=builder.StartTable();

  • 使用模板

Aspose.Words.Tables.Table table = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true);

第1个参数表示查找的节点类型是表格。

第2个参数表示在文档中查找的表格的索引,0即为文档中的第1个表格。

第3个参数表示是否返回表格中的子节点,true即表示表格中的其他节点也会返回。

三、Table中常见操作

  • 插入单元格:单元格是表格中的最小单位

builder.InsertCell();

  • 设置单元格样式

//设置单元格的边框线样式 builder.CellFormat.Borders.LineStyle = LineStyle.Single; //设置单元格边框颜色 builder.CellFormat.Borders.Color = Color.Black; //设置单元格垂直对齐方式 builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; //设置单元格宽度 builder.CellFormat.Width = 20; //设置单元格高度 builder.RowFormat.Height = 20; //设置单元格背景颜色 builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;

  • 移动光标到具体单元格:将当前光标移动到某个单元格进行操作

//tableIndex:表索引 //rowIndex:行索引 //columnIndex:列索引 //characterIndex:单元格中的字符索引 builder.MoveToCell(tableIndex,rowIndex,columnIndex,characterIndex)

  • 插入行

插入行是通过连续插入单元格实现的,用builder.EndRow()表示一行结束。

builder.InsertCell();//第1个单元格 builder.InsertCell();//第2个单元格 builder.InsertCell();//第3个单元格 ... builder.EndRow(); //一行结束

  • 复制行

//选择复制当前table的最后一行 Node lastRowNode = table.LastRow.Clone(true); //也可以复制table中已经存在的某一行 //这个地方复制的是表格的第一行 // 注:注意数组越界 Node rowNode = table.Rows[0].Clone(true); //接下来将复制的行节点插入到表格 //第一个参数Index,表示插入到表格的第几行 table.Rows.Insert(1,lastRowNode);

  • 删除行

//先找到要删除的行 Node lastRowNode = table.LastRow; //从table的行中删除 table.Rows.Remove(lastRowNode);

  • 合并单元格

合并单元格的原理:

1.水平合并(HorizontalMerge)

设置需要合并的第一个单元格的HorizontalMerge属性为CellMerge.First

后续需要合并的单元格HorizontalMerge属性为CellMerge.Previous

代码如下:

builder.CellFormat.HorizontalMerge = CellMerge.First; builder.CellFormat.HorizontalMerge = CellMerge.Previous;

2.垂直合并(VerticalMerge)

asp论坛

设置需要合并的第一个单元格的VerticalMerge属性为CellMerge.First

后续需要合并的单元格VerticalMerge属性为CellMerge.Previous

代码如下:

builder.CellFormat.VerticalMerge = CellMerge.First; builder.CellFormat.VerticalMerge = CellMerge.Previous;

  • 向特定单元格写入内容

builder.Write("内容"); builder.Writeln("内容");//带换行 builder.Writeln();//只换行

就分享到这儿了,喜欢就点个

您可以还会对下面的文章感兴趣

最新评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

使用微信扫描二维码后

点击右上角发送给好友