如何在WebControls.GridView中修改字段列

本文关键字:修改 字段 GridView WebControls | 更新日期: 2023-09-27 18:02:13

概述:使用c#,我输出一个LINQ到SQL的数据表到一个WebControls。GridView,然后将其输出到从网页提供的Excel文件。如何修改GridView中的字段?

问题: Excel截断和/或将数字字符串转换为科学记数法。

198886545467896变成1.98887E+14

为了将该字段保留为字符串,我需要将该字段包装成字符串公式,如下所示,以便Excel将按预期显示。

= " 198886545467896 ">

strong>问题:我如何包装字段数据在一个特定的GridView列与="[number]"?

这是我的相关c#:

public void DownloadExcelReport(int id)
    {
        // See: http://www.codeshelve.com/code/details/54/export-to-excel-in-asp-net-mvc
        // Or: http://www.billsternberger.net/asp-net-mvc/export-to-excel-or-csv-from-asp-net-mvc-with-c/
        // Or: http://blog.wiredworx.co.uk/website-and-seo/c-tutorials-and-tips-visual-studio/exporting-to-an-excel-file-from-asp-net-mvc/
        // same solution - discussed differently            
        IEnumerable<Customer> customers = Db.Customers(id);
        // Create a grid and bind the customer data to it.
        var grid = new System.Web.UI.WebControls.GridView();
        grid.DataSource = customers;
        grid.DataBind();
        // TODO: I need to wrap the data in column 2 with =" "
        // UPDATE: INSERT the code from the accepted answer below right here
        // Prep the http response to return an excel mime type file
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
        Response.ContentType = "application/excel";
        // Output the grid via the html writer to the response
        StringWriter sw = new StringWriter();
        var htw = new System.Web.UI.HtmlTextWriter(sw);
        grid.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

更新:回想起来,这可以写得更简单,以隔离特定的问题:GridView是笨拙的导航。然而,有一个完整的解决方案,如何从一个Linq到Sql表输出到一个Excel文件,以供以后参考,这是很好的。

如何在WebControls.GridView中修改字段列

像这样?

System.Web.UI.WebControls.GridView() test = new System.Web.UI.WebControls.GridView();
for (int i = 0; i < grid.Rows.Count; i++)
{
    test.Rows[i].Cells[<yer column index>].Text = "=/"" + test.Rows[i].Cells[<yer column index>].Text + "/"";
}

参见http://www.highoncoding.com/Articles/197_Extensive_Study_of_GridView_Export_to_Excel.aspx