Here is code I have used before that works. The issue is you need to get that style that you are applying wrapped around the cells. In your case you are just dumping it into the Response but not actually applying it to any cells. This should work:
private void ExportGrid(string fileName)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
DataTable dt = (DataTable)DataGrid1.DataSource;
foreach (DataGridItem itm in DataGrid1.Items)
{
for (int i = 0; i < itm.Cells.Count; i++)
{
TableCell tc = itm.Cells[i];
switch dt.Columns[i].DataType.ToString().ToLower())
{
case "system.string":
tc.Attributes.Add("class", "text");
break;
case "system.datetime":
tc.Attributes.Add("class", "dt");
break;
case "system.decimal":
tc.Attributes.Add("class", "num");
break;
default:
break;
}
}
}
DataGrid1.RenderControl(htw);
StringBuilder sb = new StringBuilder();
sb.Append(@"<style> ");
sb.Append(@" .text { mso-number-format:\@; } ");
sb.Append(@" .num { mso-number-format:0\.00; } ");
sb.Append(@" .dt { mso-number-format: ’Short Date’; } ");
sb.Append(@"</style>");
Response.Write(sb.ToString());
Response.Write(sw.ToString());
Response.Flush();
Response.End();
}
Sorry, the formatting didn't paste in too well.