/// <summary> /// 将DataTable 导出为EXCEL,并直接提供下载 /// </summary> /// <param name="ds">需要导处的DataTable</param> /// <param name="fileName">到处生成的文件名</param> /// public bool ExportExcelByDataTable(DataTable dt, string fileName) { try { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Charset = "utf-7"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7"); HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; StringWriter stringWrite = new StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); DataGrid dg = new DataGrid(); dg.HeaderStyle.CssClass = "dgHead"; dg.DataSource = dt; dg.DataBind(); dg.RenderControl(htmlWrite); HttpContext.Current.Response.Write(stringWrite.ToString()); HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls"); HttpContext.Current.Response.Charset = "gb2312"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); HttpContext.Current.Response.End(); return true; } catch { return false; } }