【ASP.NET】DataTable导出EXCEL,弹窗提示下载保存(完整代码)
//新建ASPX protected void Page_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); DataColumn dc1 = new DataColumn("name", Type.GetType("System.String")); DataColumn dc2 = new DataColumn("sex", Type.GetType("System.String")); DataColumn dc3 = new DataColumn("age", Type.GetType("System.String")); dt.Columns.Add(dc1); dt.Columns.Add(dc2); dt.Columns.Add(dc3); object[, ,] arrStr = { { { "Lily", "Females", "20" } }, { { "Jack", "Males", "25" } }, { { "Bob", "Males", "30" } } }; for (int i = 0; i < arrStr.GetLength(0); i++) { for (int j = 0; j < arrStr.GetLength(1); j++) { DataRow dr = dt.NewRow(); for (int k = 0; k < arrStr.GetLength(2); k++) { dr[k] = arrStr[i, j, k]; } dt.Rows.Add(dr); } } DataToExcel(dt, "导出EXCEL" + DateTime.Now.ToString("yyyyMMdd"), null); } public void DataToExcel(DataTable dt, string FileName, int[] indexs) { if (dt == null) return; if (dt.Rows.Count == 0) { return; } try { System.Web.UI.WebControls.GridView GVOutPut= new System.Web.UI.WebControls.GridView(); GVOutPut.Visible = true; GVOutPut.RowDataBound += new GridViewRowEventHandler(RowDataBound); GVOutPut.DataSource = dt; GVOutPut.DataBind(); System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.Buffer = true; System.Web.HttpContext.Current.Response.Charset = "UTF-8"; System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName + ".xls", System.Text.Encoding.UTF8)); System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel"; GVOutPut.EnableViewState = false; System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); GVOutPut.RenderControl(oHtmlTextWriter); System.Web.HttpContext.Current.Response.Write(@"<style> .text {mso-number-format:\@; } </style> "); System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString()); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.Close(); GVOutPut.DataSource = null; GVOutPut.Visible = false; } catch (Exception ex) { throw ex; } } static void RowDataBound(object sender, GridViewRowEventArgs e) { for (int i = 0; i < e.Row.Cells.Count; i++) { if (e.Row.RowType == DataControlRowType.DataRow) e.Row.Cells[i].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); } }
效果如图: