如何修改WebControls.GridView中的字段列?

时间:2011-07-14 22:55:12

标签: c# gridview export-to-excel

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

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

198886545467896变成1.98887E + 14

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

=“198886545467896”

问题:如何使用=“[number]”将字段数据包装到特定的GridView列中?

这是我的相关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文件供以后参考,这是很好的。

2 个答案:

答案 0 :(得分:0)

这样的东西?

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 + "/"";
}

答案 1 :(得分:0)