在导出的点击事件中,代码如下:
//指定导出对应单元格为文本样式
string style = @"<style> .test { vnd.ms-excel.numberformat:@; } </style> ";
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvwCheckExcepton.RenderControl(htw);
Response.Write(style);//输出样式
Response.Write(sw.ToString());//输出内容
Response.End();
在 gridview事件为RowDataBound指定哪些列需要指定格式
protected void gvwCheckExcepton_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Attributes.Add("class", "test");//前面参数是类,后面参数是样式test是上面样式定义的名称,相当于class=test;
e.Row.Cells[1].Attributes.Add("class", "test");
e.Row.Cells[2].Attributes.Add("class", "test");
}
}
如果绑定错误,需要在后台类里添加这个方法
public override void VerifyRenderingInServerForm(Control control)
{
}