本小节主要介绍如何将DataTable表中的数据导入到excel中去。主要是先通过将DataTable数据表中的数据绑定到GridView上,在将GridView中的数据到处成excel的形式。
实例代码如下: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;
//Response.ContentType = "application/vnd.ms-excel";
Response.ContentType = "application/vnd.ms-word";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Charset = "";
this.EnableViewState = false;
StringWriter oStringWriter = new StringWriter();
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
DataGrid dg = new DataGrid();
dg.DataSource = dataTable1; //返回DataTable
dg.DataBind();
dg.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();