In my C# (.NET 4.5) Windows Forms app using Excel Interop, I adapted the code from here like so (removing redundant things grayed out by Resharper, and add "Type." before the "missing" args (and changing their case to upper):
private void WriteListObjectTestSheet()
{
_xlSheetPlatypus.Cells[5, 1] = "Apple";
_xlSheetPlatypus.Cells[6, 1] = "Strawberry";
_xlSheetPlatypus.Cells[7, 1] = "Cashew";
_xlSheetPlatypus.Cells[8, 1] = "Kumquat";
_xlSheetPlatypus.Cells[9, 1] = "Pomegranate";
_xlSheetPlatypus.Cells[10, 1] = "Banana";
_xlSheetPlatypus.Cells[11, 1] = "Pineapple";
_xlSheetPlatypus.Cells[12, 1] = "Kiwi";
_xlSheetPlatypus.Cells[13, 1] = "Huckleberry";
_xlSheetPlatypus.Cells[14, 1] = "Gooseberry";
Excel.ListObject fruitList =
_xlSheetPlatypus.
ListObjects.Add(Excel.XlListObjectSourceType.xlSrcRange,
_xlSheetPlatypus.Range[
_xlSheetPlatypus.Cells[4, 1],
_xlSheetPlatypus.Cells[4, 1]],
Type.Missing, Excel.XlYesNoGuess.xlNo);
}
The ListObject is added at row 4, column 1 (or "A") as desired, and the "fruits" are written into the cells, but not starting at row 5 (where "Apple" should be) but at row 6, as you can see here (unwanted blank row highlighted):
There may be a (a lot more) to it, but this may be at least part of the reason why the ListObject has no idea what to sort and filter, as evidenced by the options it affords when it is clicked as seen here:
Why is a blank row 5 added, and how can I prevent that?
When you create a
ListObject
from a range and saying the table has no header, It shifts the range one row down and add aColumn1
cell.In the above code you said create a table from
[4,1]
to[4,1]
and you said the table has no headers, So it creates a table with one row and adds aColumn1
header and shifts all things 1 row down. So the result is what you said to excel to do for you.You can correct it by specifying the correct range and saying you have a header.
In the below code, I first add a
Header
at[4,1]
and then add fruits and at last create the list from[4, 1]
to[14, 1]
, and saying the table has headers. So it keeps my header.