/// <summary> /// 导出Excel文件,并自定义文件名 /// </summary> /// <param name="dtData">数据源</param> /// <param name="FileName">导出文件名称</param> /// <param name="numberformat">需要处理科学计数法的列的下标</param> public static void DataTable3Excel(DataTable dtData, String FileName,string numberformat) { GridView dgExport = null; HttpContext curContext = HttpContext.Current; StringWriter strWriter = null; HtmlTextWriter htmlWriter = null; if (dtData != null) { curContext.Response.Clear(); HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8); curContext.Response.AddHeader("content-disposition", "attachment;filename="" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls""); curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.Charset = "utf-8"; curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); strWriter = new StringWriter(); htmlWriter = new HtmlTextWriter(strWriter); dgExport = new GridView(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); //判断是否存在需要处理科学计数法的列,存在则进行相对应的列的处理,处理为“以文本形式存储的数字” if(numberformat!="") { string[] arraystr = numberformat.Split(','); foreach (GridViewRow dg in dgExport.Rows) { for (int i = 0; i < arraystr.Length; i++) { dg.Cells[Convert.ToInt32(arraystr[i])].Attributes.Add("style", "vnd.ms-excel.numberformat: @;"); } } } dgExport.RenderControl(htmlWriter); curContext.Response.Write("<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=utf-8"/>" + strWriter.ToString()); curContext.Response.End(); } }