/// <summary> /// Fill data from lists of items into sourceStream with tableName tag and list of column names. /// </summary> /// <param name="items">The list of data items that need fill into sourceStream.</param> /// <param name="sourceStream">The stream source that is needed to fill.</param> /// <param name="tableName">The name of control that contrain for data table.</param> /// <param name="columns">The list of column name.</param> public void FillDataListOfObject(IEnumerable items, Stream sourceStream, string tableName, string[] columns, string[] widths = null) { if (items != null) { if (sourceStream != null) { //use OpenXml to process using (WordprocessingDocument word = WordprocessingDocument.Open(sourceStream, true)) { var part = word.MainDocumentPart; // SdtBlock block = part.Document.Body.Descendants<SdtBlock>().Where(p => p.SdtProperties.GetFirstChild<Tag>().Val == tableName).FirstOrDefault(); SdtElement tableElement = part.Document.Body.Descendants <SdtBlock>().Where(p => p.SdtProperties.GetFirstChild <Tag>().Val == tableName).FirstOrDefault(); if (tableElement == null) { tableElement = part.Document.Body.Descendants <SdtRun>().Where(p => p.SdtProperties.GetFirstChild <Tag>().Val == tableName).FirstOrDefault(); } if (tableElement != null) { var table = NewTable(columns, widths); #region Fill data foreach (var item in items) { TableRow dataRow = NewEmptyRow(); string[] stringValues = GetStringValuesFromObject(item); if (widths != null) { for (var i = 0; i < columns.Length; i++) { var value = stringValues[i]; //create cell object and its properties TableCell tableCellData = NewTableCellData(value, widths[i]); // add to row dataRow.Append(tableCellData); } } else { for (var i = 0; i < columns.Length; i++) { var value = stringValues[i]; //create cell object and its properties TableCell tableCellData = NewTableCellData(value); // add to row dataRow.Append(tableCellData); } } table.Append(dataRow); } #endregion tableElement.RemoveAllChildren(); tableElement.Append(table); part.Document.Save(); } } } } }