1.替换模板的内容(不重复的没有问题)
2.现在重复的出现问题,表格的复制一直出现问题。
/// <summary> /// 替换文件 /// </summary> /// <param name="dt">要更新的数据</param> /// <param name="expPairColumn">当前要替换的数据字典</param> /// <returns></returns> private static bool GenerateTable(DataTable dt, Dictionary<string, string> expPairColumn,int index) { try { int tableNums = dt.Rows.Count; //获取所有表格 NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //获取第几个表格 Table table = allTables[index] as Table; Table tableClone = (Table)table.Clone(true); //Dictionary<string, object> dc = new Dictionary<string, object>(); for (int i = 0; i < tableNums; i++) { //dc.Clear(); if (i == 0) { foreach (string key in expPairColumn.Keys) { var value = dt.Rows[i][expPairColumn[key]].ToString(); var repStr = string.Format("{0}", key); doc.Range.Replace(repStr, value.ToString(), false, false); } continue; } table.ParentNode.InsertAfter(tableClone,table); //foreach (string key in expPairColumn.Keys) //{ // var value = dt.Rows[i][expPairColumn[key]].ToString(); // var repStr = string.Format("{0}", key); // doc.Range.Replace(repStr, value, false, false); //} } // Insert an empty paragraph between the two tables or else they will be combined into one //table.ParentNode.InsertAfter(new Paragraph(doc), table); // Insert the cloned table into the document after the original //foreach (Cell cell in tableClone.GetChildNodes(NodeType.Cell, true)) // cell.RemoveAllChildren(); return true; } catch (Exception ex) { return false; } }
这里涉及到多个表格,后面的表格总是内容重复和内容缺少
模板内容
经过复制后的内容
正常情况是应该有6条数据的,但是我代码测试的时候循环了6次,只复制了粘贴了一次。
1 int tableNums = dt.Rows.Count; 2 3 //获取所有表格 4 NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); 5 6 //获取第几个表格 7 Table table = allTables[index] as Table; 8 Table tableClone = (Table)table.Clone(true); 9 10 for (int i = 0; i < tableNums; i++) 11 { 12 if (i == 0) 13 { 14 foreach (string key in expPairColumn.Keys) 15 { 16 var value = dt.Rows[i][expPairColumn[key]].ToString(); 17 var repStr = string.Format("{0}", key); 18 doc.Range.Replace(repStr, value.ToString(), false, false); 19 } 20 continue; 21 } 22 23 Table tableClone1 = (Table)tableClone.Clone(true); 24 25 table.ParentNode.InsertAfter(tableClone1, table); 26 27 foreach (string key in expPairColumn.Keys) 28 { 29 var value = dt.Rows[i][expPairColumn[key]].ToString(); 30 var repStr = string.Format("{0}", key); 31 doc.Range.Replace(repStr, value, false, false); 32 } 33 }