Search code examples
c#linqexport-to-excel

Export to Excel - How to dynamically set header text using LINQ?


My below code is working well except for one slight issue. When I open the excel sheet, the column headers are pulling directly from the code below I.E.data.FleetNumber displays as FleetNumber for the column header. Is it possible to overwrite this? E.G I want it to display Fleet No.

I've done a lot of searching but I cant find an answer. Any help is appreciated.

    public void ExportToBeDoneVehiclesToExcel()
    {
        int count = 10;

        var grid = new System.Web.UI.WebControls.GridView();

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        var list = vehicleBusinessLogic.GetToBeDoneVehicles(count);
        grid.DataSource = from data in list
                            select new
                            {
                                data.RegistrationID,
                                data.FleetNumber,
                                data.VIN,
                                data.LocationDescription,
                                data.ServiceDescription,
                                data.NextInspectionDueDate
                            };
        grid.DataBind();

        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=Exported_ToBeDoneVehicles.xls");
        Response.ContentType = "application/excel";

        grid.RenderControl(htw);

        Response.Write(sw.ToString());
        Response.End();
    }

Solution

  • i can't test this but it seems logical to me

    try specifying the variables names in the list

    grid.DataSource = from data in list
                            select new
                            {
                                Reg = data.RegistrationID,
                                FleetNumber = data.FleetNumber,
                                VIN = data.VIN,
                                LocationDescription = data.LocationDescription,
                                ServiceDescription = data.ServiceDescription,
                                NextInspectionDueDate = data.NextInspectionDueDate
                            };