本文发表在 rolia.net 枫下论坛判断处理就按照深蓝的办法,很不错。render GridView to excel 的code:
Public void SaveBtn_Click(object sender,EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Locations.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
Public override void VerifyRenderingInServerForm( Control control)
{
}
但这里有个trick,我曾经屡试屡败,导致最后放弃而使用CSV的办法。上面的代码在我的vs2008里报错,需要在Page directive里关闭EventValidation,像这样:
<%@ Page Language="C#" EnableEventValidation="false" ...>更多精彩文章及讨论,请光临枫下论坛 rolia.net
Public void SaveBtn_Click(object sender,EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Locations.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
Public override void VerifyRenderingInServerForm( Control control)
{
}
但这里有个trick,我曾经屡试屡败,导致最后放弃而使用CSV的办法。上面的代码在我的vs2008里报错,需要在Page directive里关闭EventValidation,像这样:
<%@ Page Language="C#" EnableEventValidation="false" ...>更多精彩文章及讨论,请光临枫下论坛 rolia.net