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

时间:2017-03-27 14:22:09

标签: c# linq export-to-excel

我的下面代码运行良好,除了一个小问题。当我打开excel表时,列标题直接从下面的代码中拉出.E。data.FleetNumber显示为列标题的FleetNumber。 有可能覆盖这个吗? E.G我希望它显示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();
    }

1 个答案:

答案 0 :(得分:2)

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

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

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