今天研究了一下 导出GridView到Excel 的方法,现在分享以下:
前台界面控件:一个Gridview,一个TextBox和一个Buttion按钮。
后台代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
public const string strCon="server=.;database=card;user=sa;pwd=";//数据库连接语句
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strCon);
con.Open();
string sql = "select * from card";
SqlDataAdapter sda = new SqlDataAdapter(sql,con);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
//输入导出的Excel的文件名
string fileName = TextBox1.Text;
//调用方法
ToExcel(GridView1,fileName);
}
public static void ToExcel(System.Web.UI.Control ctl, string FileName)
{
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName + ".xls");
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
//必须有以下代码,否则报错!
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
}