title: Create OpenXML Table With C#
body: <p>I'm having issues making an actual table in my excel file.  The file is created and all the data is there, but when I open the file the table definition doesn't exist.  I'm using this method to try and turn the data range into a table.</p>
  
  <pre class="lang-cs prettyprint-override"><code>    private static Table CreateTable(string tableRange, IEnumerable&lt;string&gt; headers)
      {
          var table = new Table {
              Id = 1,
              Name = "Table 1",
              DisplayName = "Table 1",
              Reference = tableRange,
              TotalsRowShown = false,
              HeaderRowFormatId = 0
          };
          table.AddNamespaceDeclaration("x", "http://schemas.openxmlformats.org/spreadsheetml/2006/main");
  
          UInt32Value i = 1;
  
          var columns = new TableColumns();
          foreach (var header in headers) {
              columns.Append(new TableColumn {
                  Id = i++,
                  Name = header
              });
          }
  
          var style = new TableStyleInfo {
              Name = "TableStyleMedium2",
              ShowFirstColumn = false,
              ShowLastColumn = false,
              ShowRowStripes = true,
              ShowColumnStripes = false
          };
  
          table.Append(new AutoFilter { Reference = tableRange });
          table.Append(columns);
          table.Append(style);
  
          return table;
      }
  </code></pre>
  
  <p>The <code>tableRange</code> variable is a simple excel range string, like "A1:D27".  I'm trying to add it to the worksheet like so:</p>
  
  <pre class="lang-cs prettyprint-override"><code>var tableDefinitionPart = worksheetPart.AddNewPart&lt;TableDefinitionPart&gt;();
  tableDefinitionPart.Table = CreateTable(tableRange, headers);
  </code></pre>
  
  <p>I'm not getting any errors when I open the file.</p>
  
  <p>If I open the file with the XML Productivity tool and click on the "x:table (Table)" part within the worksheet I see this:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;x:table xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="1" name="Table 1" displayName="Table 1" ref="A1:Z2" totalsRowShown="0" headerRowDxfId="0"&gt;
    &lt;x:autoFilter ref="A1:Z2" /&gt;
    &lt;x:tableColumns&gt;
      &lt;x:tableColumn id="1" name="Lab Name" /&gt;
      ....
      &lt;x:tableColumn id="26" name="Description" /&gt;
    &lt;/x:tableColumns&gt;
    &lt;x:tableStyleInfo name="TableStyleMedium2" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0" /&gt;
  &lt;/x:table&gt;
  </code></pre>
  
  <p>So it seems like I'm putting something properly into the file.  It's just not an actual "table" as far as Excel is concerned.</p>