ASP.net 把 DataGrid 数据导出到 Excel .
protected void ExportExcel(DataGrid dtgList, string strFileName)
{
DataTable dt = (DataTable)this.Session["GridToExcel"];
if (dt==null) return;
Response.Clear();
Response.Buffer = true;
Response.Charset = "gb2312";
Response.AppendHeader("Content-Disposition", "online; filename=" + this.GetFileName(strFileName) + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.ContentType = "application/ms-excel";
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);
dtgList.AllowPaging = false;
// dtgList.DataSource = dt;
// dtgList.DataBind();
dtgList.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.Buffer = false;
Response.End();
}
{
DataTable dt = (DataTable)this.Session["GridToExcel"];
if (dt==null) return;
Response.Clear();
Response.Buffer = true;
Response.Charset = "gb2312";
Response.AppendHeader("Content-Disposition", "online; filename=" + this.GetFileName(strFileName) + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.ContentType = "application/ms-excel";
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);
dtgList.AllowPaging = false;
// dtgList.DataSource = dt;
// dtgList.DataBind();
dtgList.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.Buffer = false;
Response.End();
}