导出到 Excel - 如何使用 LINQ 动态设置 header 文本?

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

除了一个小问题外,我的以下代码运行良好。当我打开 excel sheet 时,header 列直接从 I.E.data.FleetNumber 下方的代码中提取,显示为 header 列的 FleetNumber。 可以覆盖这个吗?例如,我希望它显示 Fleet No.

我已经进行了很多搜索,但找不到答案。感谢任何帮助。

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

我无法对此进行测试,但对我来说这似乎合乎逻辑

尝试在列表中指定变量名称

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