I have a requirement in which I am cloning word table into multiple table based on count and inserting in to word document. If I have 5 record it should add five table using existing table clone and replace token inside tables. It is adding 5 tables but it is replacing all five tables' content with the last record so all five tables have the same data as last row.
//Main code
string tableInnerText = tblMain.InnerText;
List<string> fieldsList = GetFieldList(tableInnerText, repeatedTableListName);
var parentParagraph = printBookmarkStart.Parent;
tbl[0].Remove();
for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
{
if (pageBreak.ToUpper() == "YES" && rowIndex > 0)
{
_wordDoc.MainDocumentPart.Document.Body.InsertAfter(new Paragraph(new Run(new Break() { Type = BreakValues.Page })), parentParagraph);
}
tblMainTmp = (Table)tblMain.Clone();
_wordDoc.MainDocumentPart.Document.Body.InsertAfter<Table>(tblMainTmp, parentParagraph);
_wordDoc.MainDocumentPart.Document.Save();
UpdateRepeatedTable(dt.Rows[rowIndex], dt, rowIndex, fieldsList, repeatedTableListName);
}
[...]
private void UpdateRepeatedTable(DataRow dr, DataTable dt, int dataRowIndex, List<string> tableColumnsList, string repeatedTableListName)
{
try
{
DataTable dtFunction = GetFunctionDataTable(tableColumnsList, repeatedTableListName);
for (int j = 0; j < tableColumnsList.Count; j++)
{
string dtColumnName = ParseRelatedListFieldName(tableColumnsList[j], repeatedTableListName, true);
string dtColumnValue = dr[dtColumnName].ToString();
string formatValue = string.Empty;
string replaceValue = dtColumnValue;
//TODO: Check if fields a function field
DataRow[] findRow = dtFunction.Select(string.Format("FieldName='{0}'", tableColumnsList[j]));
bool bIsCheckBoxField = false;
if (findRow.Length > 0)
{
bIsCheckBoxField = (findRow[0]["FunctionName"].ToString().ToUpper() == "CHECKBOX" ? true : false);
formatValue = findRow[0]["Format"].ToString();
replaceValue = GetFunctionValue(dt, 0, findRow[0], ""/*, null*/);
}
_clsLog.WriteMessage("Replacing " + tableColumnsList[j] + " with " + replaceValue, ClsLog.LogType.Log);
SearchAndReplacer.SearchAndReplace(_wordDoc, tableColumnsList[j], replaceValue, true);
if (bIsCheckBoxField == true)
{
ProcessStandardFieldCheckBox(/*wordApp,*/ dtColumnValue, formatValue);
}
}
}
catch (Exception ex)
{
_clsLog.WriteMessage(ex);
}
}
http://www.ericwhite.com/blog/search-and-replace-text-in-an-open-xml-wordprocessingml-document/
I am able to resolved this issue using DocumentAssembler (http://www.ericwhite.com/blog/documentassembler-developer-center/) in open-xml-powertools, which is suggested by Eric White.
DocumentAssembler is providing verity of option to process document for repeating contents, tables, Match conditions.