protected void btnToExcel_Click(object sender, EventArgs e)
{
this.toExcelClk(this.gvUser);
}
/// <summary>
/// 导出EXCEL 复写方法
/// </summary>
/// <param name="control"></param>
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
private void ToExcel(Control ctl, string FileName)
{
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
/// <summary>
/// 导出为Excel
/// </summary>
/// <param name="ckbSelect">选择的复选框,1为导出当前选择行,2为导出当前页,3为导出所有记录</param>
private void toExcelClk(GridView gvw)
{
gvw.AllowPaging = false;
gvw.AllowSorting = false;
int i = -1;
foreach (GridViewRow gvwRow in this.gvUser.Rows)
{
i++;
if (((CheckBox)gvwRow.FindControl("cbSelect")).Checked)
{
gvw.Rows[i].Visible = true;
}
else
{
gvw.Rows[i].Visible = false;
}
}
gvw.Columns[0].Visible = false;//隐藏选择列,不导出选择列
gvw.Columns[8].Visible = false;
ToExcel(gvw, "sdtcUser.xls");
gvw.AllowPaging = true;
gvw.AllowSorting = true;
gvw.Columns[0].Visible = true;//恢复选择列为可见
gvw.Columns[8].Visible = true;
this.BindGVUser(GetCondition());
}
注意:
如果运行时报错:只能在执行 Render() 的过程中调用 RegisterForEventValidation
则在页面上加入 EnableEventValidation="false" 即可解决此问题