如何把数据到GridView然后引导Excel

复制代码代码如下所示:
使用系统;
使用system.collections.generic;
使用LINQ系统;
使用系统;
使用system.web.ui;
使用system.web.ui.webcontrols;
使用system.data.sqlclient;
使用系统数据;

公共部分类_default:system.web.ui.page
{
protected void page_load(object sender,EventArgs e)
{
字符串sqlconn == = DB数据库服务器。;;综合安全= SSPI ;
从表中选择顶部10 *;

SqlConnection myconnection =新的SqlConnection(sqlconn); / /创建数据库连接的例子

(myconnection。打开); / /打开数据库

SqlCommand mycommand =新SqlCommand(SQL,myconnection); / /创建SQL实例,执行一个SQL


SqlDataAdapter适配器=新SqlDataAdapter(SQL); / /创建一个数据适配器
adapter.selectcommand = mycommand; / /属性从数据源检索记录


数据集(数据集);新MYDS = / /创建一个数据集实例
适配器。填充(MYDS); / /填充数据集

gridview1.datasource = MYDS。表{ 0 }。defaultview; / /
gridview1.databind();

/ / datatoexcel(测试cxcel
(myconnection。关闭); / /关闭数据库连接
}
公共无效DataToExcel(文件名字符串,GridView mygridview)
{
定义文档类型、字符编码
反应清楚();
响应。缓冲区= false;
/ / response.charset =UTF-8;
响应。字符集=GB2312;
下面的行非常重要,因为附件参数表示下载附件,您可以在线更改在线打开。
/ /文件名= fileflow.xls指定输出文件名,注意扩展和指定文件类型相匹配,可以be.doc.xls.txt | | .htm | | | |
response.appendheader(内容配置
response.contentencoding = system.text.encoding.getencoding(UTF-8);
/ / response.contentencoding = system.text.encoding.getencoding(我);
/ / response.contenttype指定文件类型的应用程序/ MS Excel应用程序/ MS Word应用程序/ MS / MS txt应用HTML | | | | | | | |或其他浏览器可以直接支持文件
response.contenttype =应用/ MS Excel;
this.enableviewstate = false;
/ / system.globalization.cultureinfo mycitrad =新system.globalization.cultureinfo(zh-cn
定义输入流
system.io.stringwriter ostringwriter =新system.io.stringwriter();
system.web.ui.htmltextwriter ohtmltextwriter =新system.web.ui.htmltextwriter(ostringwriter);
数据绑定到输入输出流的目标。
mygridview.rendercontrol(ohtmltextwriter);
响应。写(ostringwriter.tostring());
响应(完);
}

以下为声明必须添加,否则将窗体标记必须放在一个错误Runat=服务器中。
公共覆盖空洞verifyrenderinginserverform(控制)
{
}

单击、生成excel
protected void button1_click(object sender,EventArgs e)
{
datatoexcel(测试cxcel
}
}