EPPlus custom header column names

Muflix picture Muflix · Feb 10, 2016 · Viewed 10.9k times · Source

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

Answer

Patrick picture Patrick · Mar 23, 2018

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; }
}