日期:2014-05-18 浏览次数:20558 次
public static void Download_Excel(DataTable dt,string filename) { System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls")); string str_column = ""; string ls_item = ""; int i = 0; foreach(DataColumn dc in dt.Columns) { str_column += "\t" + dc.ColumnName; } str_column = str_column.Remove(0,1) + "\n"; System.Web.HttpContext.Current.Response.Write(str_column); foreach(DataRow row in dt.Rows) { //在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n for(i=0;i<(dt.Columns.Count-1);i++) ls_item +=row[i].ToString().Replace("\"","“") + "\t"; ls_item += row[i].ToString().Replace("\"","“") +"\n"; //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据 System.Web.HttpContext.Current.Response.Write(ls_item); ls_item=""; } System.Web.HttpContext.Current.Response.End(); }
------解决方案--------------------
导出EXCEL表
/////////////////////////////////////////////////////////////////////////////
System.Web.UI.WebControls.DataGrid dgr = new DataGrid();
dgr.DataSource = dt;
dgr.DataBind();
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + DateTime.Now.ToShortDateString() +""+".xls"+"");
HttpContext.Current.Response.Charset = "gb-2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel/ms-word";
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
dgr.RenderControl(hw);
dgr.Dispose();
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
------解决方案--------------------
http://www.ebookit.cn/177.html