#region 导出Excel方法 //导出到Excel按钮 protected void btnExport_Click(object sender, EventArgs e) { Export("application/ms-excel", "字段数据.xls"); } private void Export(string FileType, string FileName) { //清楚分页 gridView.AllowPaging = false; BindData(); Response.Clear(); Response.Buffer = true; //设定输出的字符集 Response.Charset = "GB2312"; //解决导出到Excel2007乱码问题 Response.Write("<meta http-equiv=Content-Type content=text/html;charset=GB2312>"); //假定导出的文件名为盘点结果表.xls Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString()); //解决导出到Excel2007乱码问题 Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置导出文件的格式 Response.ContentType = FileType; //关闭ViewState this.EnableViewState = false; System.IO.StringWriter stringWriter = new System.IO.StringWriter(); HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter); gridView.RenderControl(textWriter); //把HTML写回浏览器 Response.Write(stringWriter.ToString()); Response.Flush(); Response.End(); gridView.AllowPaging = true;//恢复分页 //为GridView重新绑定数据源 BindData(); } //如果没有下面方法会报错,类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内(导出Excel或Word用) public override void VerifyRenderingInServerForm(Control control) { } #endregion