using System;

using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;
using System.IO;
using System.Text; //连接Excel需要用的命名空间

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGv();
}
}

//绑定数据源

protected void BindGv()
{
gvStudents.DataSource = GetDs();
gvStudents.DataBind();
}

//获得数据源

protected DataSet GetDs()
{
string excelPath = Server.MapPath("school.xls");
string conString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelPath + "; Extended Properties=Excel 8.0;";
OleDbConnection con = new OleDbConnection(conString);
OleDbDataAdapter da = new OleDbDataAdapter("select * from [students]", con);
DataSet ds = new DataSet();
da.Fill(ds);

return ds;

}

//生成Excel

protected void btnExcel_Click(object sender, EventArgs e)
{
Export("student.xls");
}

//生成Excel的方法

private void Export(string FileName)
{
// Response.Charset = "GB2312";
// Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "p_w_upload;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = "application / ms - excel";
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
gvStudents.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}

#region **** 生成Excel必须要重写的方法 ****

//如果没有下面方法会报错类型“GridView”的控件“gvStudents”必须放在具有 runat=server 的窗体标记内
public override void VerifyRenderingInServerForm(Control control)
{

}

#endregion

}