private void Page_Load(object sender, System.EventArgs e)
{
DataSet ds = new DataSet();
sqlDataAdapter1.Fill(ds);
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
---------------------------------
下载按钮代码如下:
private void Button1_Click(object sender, System.EventArgs e)
{
//1.定义文档类型、字符编码
Response.Clear();
Response.Buffer= true;
Response.Charset="utf-8";
//attachment 参数表示作为附件下载,online在线打开
//filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt
Response.AppendHeader("Content-Disposition","online;filename=FileFlow.xls");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
//application/ms-excel, application/ms-word, application/ms-txt, application/ms-html
Response.ContentType = "application/ms-excel";
DataGrid1.EnableViewState = false;
//2.定义一个输入流
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
//3.目标数据绑定到输入流输出
this.RenderControl(oHtmlTextWriter);//this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件
Response.Write(oStringWriter.ToString());
Response.End();
}
=================================
public void ExportExcel(DataTable dt, string fileName)
{
Response.AppendHeader("Content-Disposition", "attachment;filename=fileName.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel";
DataGrid dgExport = new DataGrid();
dgExport.DataSource = dt;
dgExport.DataBind();
System.IO.StringWriter strWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(strWriter);
dgExport.RenderControl(htmlWriter);
Response.Clear();
Response.Write(@"<meta http-equiv=""Content-Type"" content=""text/html; charset=gb2312"" />");
Response.Write(strWriter.ToString());
Response.End();
}