Search code examples
c#excelvstolistobject

VSTO: Don't include column header


I'm using VSTO to bring some data from a database and displaying it on a worksheet

The user presses a button and the worksheet gets populated with some data

The problem is that when the data gets written into the worksheet it automatically includes a column header, I don't want this column header

I initially set ListObject.ShowHeaders = false; but then it includes an empty cell, I don't want an empty cell.

This is how I declare the ListObject

 private void CreateListObject()
    {
        worksheet = (Excel.Worksheet)this.Application.ActiveWorkbook.Worksheets[1];

        Worksheet extendedWorksheet = Globals.Factory.GetVstoObject(worksheet); 
        Excel.Range cell = extendedWorksheet.Range["C12", "C16"];//Obtain a range
        this.listObject = extendedWorksheet.Controls.AddListObject(cell, "Data");//Add to ListObject
        this.listObject.AutoSetDataBoundColumnHeaders = false;
        this.listObject.ShowAutoFilter = false;
        this.listObject.ShowHeaders = false; //I thought this was enough
        this.listObject.ShowTableStyleRowStripes = false;
    }

This is how I populate data

  internal void DisplayData()
    {
        try
        {
            using (MyDbContext db = new MyDbContext ())
            {
                List<Thing> things= db.Things.ToList();
                CreateListObject();

                string[] mappedColumns = { "serialNumber" };
                this.listObject.SetDataBinding(things, string.Empty, mappedColumns);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

But when the data gets displayed, it includes an empty cell:

enter image description here

How do I completely avoid that column header?


Solution

  • I am afraid that Headers of ListObject in Excel can't be removed. What you can do is to convert the ListObject to Range and then delete the very first row.

    Range rng;
    rng = this.listObject.Range;
    this.listObject.Unlist();
    rng.Rows[0].Delete();