一个.net导出excel比较简单的办法,代码如下,但必须要重写一个方法,不然在执行RenderControl(hw)这句代码时报错。
string _fileXls = string.Format("{0}{1}", "Patty Cash", DateTime.Now.ToString(CommonDefine.DATE_FORMAT_LIST));
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + _fileXls + ".xls");
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
HttpContext.Current.Response.ContentType = "application/ms-excel";
this.gvList.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
this.gvList.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
要重载的方法:
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
//base.VerifyRenderingInServerForm(control);
}