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. How do I modify a field in the GridView?
Problem: Excel is truncating and/or converting a string that is numeric to scientific notation.
198886545467896 turns into 1.98887E+14
In order to retain this field as a string, I need to wrap the field into a string formula as follows so that Excel will display it as intended.
="198886545467896"
Question: How do I wrap the field data in a specific GridView column with ="[number]"?
Here is my relevant C#:
public void DownloadExcelReport(int id)
{
// See: http://www.codeshelve.com/code/details/54/export-to-excel-in-asp-net-mvc
// Or: h开发者_Python百科ttp://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();
}
Update: in retrospect, this could have been written much more simply, to isolate the specific issue: GridView is clunky to navigate. 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.
Something like this?
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 + "/"";
}
Also see http://www.highoncoding.com/Articles/197_Extensive_Study_of_GridView_Export_to_Excel.aspx
精彩评论