- 积分
- 40165
- 好友
- 记录
- 主题
- 帖子
- 听众
- 收听
|
GridView数据导出到Word/Excel
GridView控件是集合控件,可以显示数据、修改数据,但是GridView控件控件没有办法保存数据。那么为GridView控件寻找一种保存数据的方式就很重要了。在NET2.0中加强了数据绑定控件与Office软件的结合。使得GridView控件可以借助于Office文件来保存自己的信息。
在开始写导出GridView控件中的数据代码之前,首先要把以下代码using System.IO添加到引用头文件里面。System.IO是使用Word等文件的命名空间。同时还要把using System.Data.SqlClient也添加进去。在名称为Button1对应的“Click”事件中写如下代码。
[code=csharp]protected void Button1_Click(object sender, EventArgs e)
{
//声明一个字符串
string sConnectionString;
//连接数据库字符串,连接到XBMIS数据库,用户名是sa
sConnectionString = " Data Source=.;Initial Catalog=XBMIS;User ID=sa; ";
//创建SqlConnection数据库连接对象
SqlConnection Conn = new SqlConnection(sConnectionString);
//打开Conn
Conn.Open();
//sql语句把T_YongH表中的数据信息都取出来
string commandString = "Select BianH AS 编号,ZhuCYHM AS 注册名,XingM AS 姓名,XingB AS 性别 From T_YongH";
SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, Conn);
ds_datatable ds = new ds_datatable();
//填充数据集
dataAdapter.Fill(ds, "YongH");
DataTable dataTable1 = ds.Tables["YongH"];
//清除客户端当前显示
Response.Clear();
Response.Buffer = true;
//输出类型为Word
Response.ContentType = "application/vnd.ms-word";
//输出类型为Excel
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
//设置显示的字和内容要存的形式
Response.Charset = "Word文档";
this.EnableViewState = false;
StringWriter oStringWriter = new StringWriter();
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
GridView gd = new GridView ();
//返回DataTable
gd.DataSource = dataTable1;
gd.DataBind();
gd.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
[/code]
|
|