GridView 导出Excel
前台:
<td style="width: 150px;"> <asp:Button ID="btnExcel" runat="server" Text="导出Excel/Export Excel" OnClick="btnExcel_Click" Width="100%" /> </td>
后台:
protected void btnExcel_Click(object sender, EventArgs e) { DateTime dt = System.DateTime.Now; string str = dt.ToString("yyyyMMddhhmmss"); str = str + ".xls"; gvDepartmentInfo.AllowPaging = false; gvDepartmentInfo.DataSource = GetData(); gvDepartmentInfo.DataBind(); GridViewToExcel(gvDepartmentInfo, "application/ms-excel", str); // Export(gvRecord, "application/ms-excel", str); } /// <summary> /// 将网格数据导出到Excel /// </summary> /// <param name="ctrl">网格名称(如GridView1)</param> /// <param name="FileType">要导出的文件类型(Excel:application/ms-excel)</param> /// <param name="FileName">要保存的文件名</param> public static void GridViewToExcel(Control ctrl, string FileType, string FileName) { HttpContext.Current.Response.Charset = "GB2312"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//注意编码 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); HttpContext.Current.Response.Write(tw.ToString()); HttpContext.Current.Response.End(); } public override void VerifyRenderingInServerForm(Control control) { }
posted on 2013-11-01 16:44 YoungPop_Chen 阅读(164) 评论(0) 编辑 收藏 举报