Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / Office / MS-Excel

Tip: Format an Excel Range as a Table Programatically

5.00/5 (6 votes)
26 Aug 2011CPOL 80.9K  
C# code to format a certain range of Excel cells using the Format As Table button -- but from C# interop code
Sometimes, you have a range of cells and you want to choose the Format As Table button to format the cells as a nice table.

Here's how to do that using Excel interop:

C#
public void FormatAsTable(Excel.Range SourceRange, string TableName, string TableStyleName)
{
    SourceRange.Worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange,
    SourceRange, System.Type.Missing, XlYesNoGuess.xlYes, System.Type.Missing).Name =
        TableName;
    SourceRange.Select();
    SourceRange.Worksheet.ListObjects[TableName].TableStyle = TableStyleName;
}


That's it! To apply a table style, e.g. TableStyleMedium15, to a range of cells, you say:

C#
Excel.Range SourceRange = (Excel.Range)oSheet.get_Range("A6","X10"); // or whatever range you want here
FormatAsTable(SourceRange, "Table1", "TableStyleMedium15");


The "Table1" is just a random name for the table; it's arbitrary, but every table you format must be a unique range. The table style names you can find out by recording a macro, applying the formatting by hand, and then reading off of the VBA module what style name Excel filled in once you've stopped the recording.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)