Share via


In C#, how can I create a table in excel from a range of cells?

Question

Wednesday, February 3, 2010 5:57 PM

In my C# program, I'm creating an excel file (using Microsoft.Office.Interop.Excel). In this excel file, I'd like to be able to create a table over a range of data.

Basically, I want to mimic what I can do in excel. For example, in Excel, I select a range of cells (A5-C10) and click Insert->Table. A "Create Table" dialog appears, I check that my table has headers and click ok. Now my headers act as filters where I can sort the rows.

How can I do this from C#?

Thanks,
Brandon

All replies (2)

Wednesday, February 3, 2010 8:31 PM âś…Answered | 1 vote

I don't necessarily like this, but it does work.

Code Snippet

  1. public static void SetTable(String FileName)
  2. {
  3.     xls.Application ExcelObj = new xls.Application();
  4.     ExcelObj.DisplayAlerts = false;
  5.     ExcelObj.Visible = true;
  6.     xls.Workbook eBook = ExcelObj.Workbooks.Open(FileName, 2, false,
  7.         5, "", "", true, xls.XlPlatform.xlWindows, "",
  8.         false, false, 0, false, true, 0);
  9.     xls.Worksheet ws = (xls.Worksheet)eBook.Worksheets["Sheet1"];
  10.     xls.Range tRange = ws.get_Range("A1", "C4");
  11.  
  12.     ws.ListObjects.Add(xls.XlListObjectSourceType.xlSrcRange, tRange,
  13.         Type.Missing, xls.XlYesNoGuess.xlYes, Type.Missing).Name = "TestTable";
  14.     ws.ListObjects["TestTable"].TableStyle = "TableStyleMedium3";
  15.     //ExcelObj.Workbooks.Close();
  16.     //ExcelObj.Quit();
  17. }

Thursday, February 4, 2010 5:12 PM

Thanks, that works great!