如何实现datagrid中的记录下载
我现在做了一个小程序,想实现datagrid中记录下载的功能.我下载了一段代码:导出到csv文件,存放在服务器端任一路径,然后给客户下载:
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
DataSet ds=new DataSet(); da.Fill(ds,"table1");
DataTable dt=ds.Tables["table1"];
string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+_
DateTime.Today.ToString("yyyyMMdd")+_
new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";
//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数
FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
sw.WriteLine("自动编号,姓名,年龄");
foreach(DataRow dr in dt.Rows)
{ sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]); }
sw.Close();
Response.AddHeader("Content-Disposition", "attachment;
filename=" + Server.UrlEncode(name));
Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.WriteFile(name); // 把文件流发送到客户端
Response.End();