zl程序教程

您现在的位置是:首页 >  工具

当前栏目

如何将数据绑到gridview然后导成excel

Excel数据 如何 GridView 然后
2023-06-13 09:15:18 时间
复制代码代码如下:

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Data.SqlClient;
usingSystem.Data;

publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
Stringsqlconn="Server=.;DataBase=db;IntegratedSecurity=SSPI";
stringsql="selecttop10*fromtable";

SqlConnectionmyConnection=newSqlConnection(sqlconn);//创建数据库连接实例

myConnection.Open();//打开数据库

SqlCommandmyCommand=newSqlCommand(sql,myConnection);//创建sql的实例,执行一个sql


SqlDataAdapterAdapter=newSqlDataAdapter();//创建一个sql数据适配器
Adapter.SelectCommand=myCommand;//属性设置为从数据源中检索记录


DataSetmyDs=newDataSet();//创建数据集实例
Adapter.Fill(myDs);//填充数据集

GridView1.DataSource=myDs.Tables[0].DefaultView;//
GridView1.DataBind();

//DataToExcel("测试的cxcel",GridView1);
myConnection.Close();//关闭数据库连接
}
publicvoidDataToExcel(stringfileName,GridViewmyGridView)
{
//定义文档类型、字符编码
Response.Clear();
Response.Buffer=false;
//Response.Charset="utf-8";
Response.Charset="GB2312";
//下面这行很重要,attachment参数表示作为附件下载,您可以改成online在线打开
//filename=FileFlow.xls指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc||.xls||.txt||.htm
Response.AppendHeader("Content-Disposition","attachment;filename="+System.Web.HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)+".xls");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
//Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
//Response.ContentType指定文件类型可以为application/ms-excel||application/ms-word||application/ms-txt||application/ms-html||或其他浏览器可直接支持文档
Response.ContentType="application/ms-excel";
this.EnableViewState=false;
//System.Globalization.CultureInfomyCItrad=newSystem.Globalization.CultureInfo("ZH-CN",true);
//定义一个输入流
System.IO.StringWriteroStringWriter=newSystem.IO.StringWriter();
System.Web.UI.HtmlTextWriteroHtmlTextWriter=newSystem.Web.UI.HtmlTextWriter(oStringWriter);
//将目标数据绑定到输入流输出
myGridView.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}

//下面这个空语句一定要加,否则会出现“必须放在具有runat=server的窗体标记内。”的错误
publicoverridevoidVerifyRenderingInServerForm(Controlcontrol)
{
}

//点击事件,生成excel
protectedvoidButton1_Click(objectsender,EventArgse)
{
DataToExcel("测试的cxcel",GridView1);
}
}