您的位置:首页 > 其它

DataGrid里的数据导出成xls文件

2006-02-27 13:44 453 查看
本文介绍将DataGrid里的数据导出成xls文件

代码如下:(写在导出按钮的Click事件里)

 

string conn=System.Configuration.ConfigurationSettings.AppSettings["Connection"];
try
{
SqlConnection myConn=new SqlConnection(conn);
myConn.Open();
SqlDataAdapter myDa=new SqlDataAdapter("select * from Customers",myConn);
DataSet myDs=new DataSet();
myDa.Fill(myDs,"Customers");
DataTable myDt=myDs.Tables["Customers"];
StringWriter mySw=new StringWriter();
mySw.WriteLine("CompanyName/tAddress/tCity/tCountry/tPhone");
foreach(DataRow myDr in myDt.Rows)
{
mySw.WriteLine(myDr["CompanyName"]+"/t"+myDr["Address"]+"/t"+myDr["City"]+"/t"+myDr["Country"]+"/t"+myDr["Phone"]);
}
mySw.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.Write(mySw);
Response.End();
}
catch(SqlException ex)
{
Console.WriteLine("Exception in AdminList:"+ex.Message);
}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐