GridView导出excel
Rp_GridList.AllowPaging = false;//因为GridView是分页的 开始要取消分页
Rp_GridList.DataBind();//重新绑定
GridViewToExcel(Rp_GridList, "ms-excel/msword", "商家缴费明细.xls");
Rp_GridList.AllowPaging = true;//导出之后重新开启分页
Rp_GridList.DataBind();
///数字太长会变成科学计算法 在OnRowDataBound里面改样式
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Attributes.Add("class", "text");
e.Row.Cells[1].Attributes.Add("class", "text");
e.Row.Cells[2].Attributes.Add("class", "text");
e.Row.Cells[5].Attributes.Add("class", "text");
}
}
//要重写这个方法 不然会报错 "页面没加 runat sever"
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
/// <summary>
/// 将网格数据导出到Excel
/// </summary>
/// <param name="ctrl">网格名称(如GridView1)</param>
/// <param name="FileType">要导出的文件类型(Excel:application/ms-excel)</param>
/// <param name="FileName">要保存的文件名</param>
public void GridViewToExcel(Control ctrl, string FileType, string FileName)
{
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;//注意编码
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctrl.Page.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
string style = @"<style> .text { mso-number-format:\@; } </style> ";
Response.Write(style);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}