簡體   English   中英

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

[英]How do I modify a column of fields in a WebControls.GridView?

Overview: Using C#, I'm outputting a LINQ to SQL table of data into a WebControls.GridView and then outputting it to an Excel file served from a webpage. 如何修改 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 導航笨拙。 However, it's nice to have the whole solution in how to output from a Linq to Sql table all the way to an Excel file for later reference.

像這樣的東西?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM