标签:
//gv:需要导出数据的GridView,filename:导出excel文件名
public void ExportToExcel(GridView gv, string filename) { string style = @"<style> .text { mso-number-format:\@; } </style> "; Response.ClearContent(); HttpContext.Current.Response.Charset = "UTF8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;//注意编码 Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gv.PageSize = Int16.MaxValue;
//导出之前一定要再次绑定数据源,不然导出无数据 gv.DataSource = getGridViewData(); gv.DataBind(); gv.RenderControl(htw); // Style is added dynamically Response.Write(style); Response.Write(sw.ToString()); Response.End(); }
//必须加上这个函数,函数中没有任何内容只是重载一下,不然会报错:... type ‘GridView‘ must be placed inside a form tag with runat=server. public override void VerifyRenderingInServerForm(Control control) { }
//可以在每行数据绑定的时候设置数据格式
protected void IBDetailGridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowIndex > -1) { e.Row.Cells[7].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); e.Row.Cells[8].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); } }
标签:
原文地址:http://www.cnblogs.com/wen20104659/p/5362926.html