14

I have following code, which generate me an excel with header row. The column names of header are named as variables in DataItem class.

// class for single row item
    public class DataItem
    {
        public int Number { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Country { get; set; }
    }

    // Retrive data items from database and store into conllection.
    var rows = database.GetData().ToList();

    // Create table from collection with automatic header
    ws.Cells["A1"].LoadFromCollection(rows, true, TableStyles.Medium25);

excel header output :

Number | FirstName | LastName | Country

How my output can be customized for example (spaces added etc.):

Number | First Name | Last Name | Country
Muflix
  • 6,192
  • 17
  • 77
  • 153

2 Answers2

15

Use DescriptionAttribute from System.ComponentModel namespace to set column names in the header.

public class DataItem
{
    public int Number { get; set; }

    [Description("First name")]
    public string FirstName { get; set; }

    [Description("Last name")]
    public string LastName { get; set; }

    public string Country { get; set; }
}
Patrick
  • 1,019
  • 13
  • 16
4

I have it, solution is following

ws.Cells["A1"].Value = "Number";
ws.Cells["B1"].Value = "First Name";
ws.Cells["C1"].Value = "Last Name";
ws.Cells["D1"].Value = "Country";
Muflix
  • 6,192
  • 17
  • 77
  • 153
  • 2
    Just want to add that you need to do call the LoadFromCollection method with false for the second parameter - PrintHeaders. Start from the second row and don't print the headers from the collection: workSheet.Cells[2, 1].LoadFromCollection(rows, false); – Koshera Jul 11 '17 at 21:24
  • @Koshera I am not sure if I used the second parameter, because even if the headers will be printed, I think the additional value settings will overwrite the names, but thank you for the mention of that parameter. – Muflix Jul 12 '17 at 11:32