参数说明:table :当前 document中的table对象 获取方式 如下:
Table labTable = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true);
////// 在表格中插入行 /// /// 表格对象 /// 插入表格的单元格对齐方式 /// 字体名称 /// 从当前获取表格的哪一行开始插入 /// 要插入的list /// 当前文档的document ///public static bool InsertRowToTable(Table table, ParagraphAlignment cellAlignment, string FontName, int startRow, IList list, Document doc) { try { int positionRow = startRow + 1; DataTable dataTable = ListToDataTable(list); for (int i = 0; i < dataTable.Rows.Count; i++) { Row insertRow = (Row)table.Rows[startRow].Clone(true); foreach (Cell cell in insertRow.Cells) { cell.RemoveAllChildren(); } for (int j = 0; j < dataTable.Columns.Count; j++) { var cl = insertRow.Cells[j]; Paragraph p = new Paragraph(doc); p.ParagraphFormat.Alignment = cellAlignment; p.ParagraphFormat.Style.Font.Name = FontName; p.AppendChild(new Run(doc, dataTable.Rows[i][j].ToString())); cl.AppendChild(p); } table.Rows.Insert(positionRow, insertRow); positionRow++; } return true; } catch (Exception e) { throw e; } } /// /// C# List转换成DataTable 列顺序根据创建Model顺序 /// /// ///public static DataTable ListToDataTable(IList list) { DataTable result = new DataTable(); if (list.Count > 0) { PropertyInfo[] propertys = list[0].GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { //获取类型 Type colType = pi.PropertyType; //当类型为Nullable<>时 if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } result.Columns.Add(pi.Name, colType); } for (int i = 0; i < list.Count; i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in propertys) { object obj = pi.GetValue(list[i], null); tempList.Add(obj); } object[] array = tempList.ToArray(); result.LoadDataRow(array, true); } } return result; }
Aspose.word根据datatable创建表格在表格末尾添加行
////// 根据datatable创建表格(末尾添加) /// /// 当前doc中的table /// 数据list /// 文档doc ///public static bool CreateTable(Table table, IList list, Document doc) { try { DataTable dataTable = ListToDataTable(list); for (int i = 0; i < dataTable.Rows.Count; i++) { //Row LastRow = (Row)table.Rows[12].Clone(true); Row LastRow = (Row)table.LastRow.Clone(true); foreach (Cell cell in LastRow.Cells) { cell.RemoveAllChildren(); } for (int j = 0; j < dataTable.Columns.Count; j++) { var cl = LastRow.Cells[j]; Paragraph p = new Paragraph(doc); p.AppendChild(new Run(doc, dataTable.Rows[i][j].ToString())); cl.AppendChild(p); } table.AppendChild(LastRow); } return true; } catch (Exception e) { throw e; } }



