ASP.NET - C# - set gridview cell as text and export to excel as text
I am populating a grid with data from a database. I am then exporting that data to excel. The problem I am having is that a column will have a value "001" but it exports as "1". How can I define it so it is text when it exports?
protected void ExportToExcel(DataTable dt) { string sFileName = "Data_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".xls"; GridView gv = new GridView(); gv.AllowPaging = false; gv.DataSource = dt; gv.DataBind(); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.Buffer = true; Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sFileName)); Response.ContentType = "application/vnd.ms-excel"; //Response.ContentType = "application/vnd.openxmlformats"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); //Change the Header Row Foreground to white color gv.HeaderRow.Style.Add("color", "#FFFFFF"); //Applying stlye to gridview header cells for (int i = 0; i < gv.HeaderRow.Cells.Count; i++) { //Change to Blue gv.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1"); } int j = 1; //This loop is used to apply stlye to cells based on particular row foreach (GridViewRow gvrow in gv.Rows) { gvrow.BackColor = Color.White; if (j <= gv.Rows.Count) { if (j % 2 != 0) { for (int k = 0; k < gvrow.Cells.Count; k++) { gvrow.Cells[k].Style.Add("background-color", "#EFF3FB"); } } } j++; } gv.RenderControl(htw); Response.Write(sw.ToString()); Response.Flush(); Response.End(); }
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
also, if you need to pad leading zeros or format, check this info:
http://msdn.microsoft.com/en-us/library/dd260048.aspx