There is a problem with the answer above. It works if the number of columns and names/ordinals of those columns have not changed, but will fail if there is a change to schema. There are a few things that need to be updated to ensure that the file is Excel compliant.
- Set the
count
attribute on thetableColumns
element: Syncronise the column headers in your table with the column elements inside the
tableColumns
elementvar table = sheet.Tables.First(); var tableElement = table.TableXml.DocumentElement; tableElement.Attributes["ref"].Value = rng.Address; var columnNode = tableElement["tableColumns"]; columnNode.Attributes["count"].Value = rng.End.Column.ToString(); for (int i = 0; i < dataTable.Columns.Count; i++) { if(columnNode.ChildNodes.Count == i) { var clonedNode = columnNode.ChildNodes[i - 1].CloneNode(true); clonedNode.Attributes["id"].Value = (i + 1).ToString(); clonedNode.Attributes["name"].Value = dataTable.Columns[i].ColumnName; columnNode.AppendChild(clonedNode); } else { columnNode.ChildNodes[i].Attributes["name"].Value = dataTable.Columns[i].ColumnName; } if(i == reportInstance.Data.Columns.Count - 1) { while(columnNode.ChildNodes.Count > reportInstance.Data.Columns.Count) { columnNode.RemoveChild(columnNode.ChildNodes[i + 1]); } } } if (tableElement["autoFilter"] != null) { tableElement["autoFilter"].Attributes["ref"].Value = rng.Address; }