查询数据导出为EXCEL保存到客户端
Admin | 2007-10-8 19:03:01 | 被阅次数 | 8793
大体代码如下,相关地方敬请自行修改:
//SqlDataAdapter mycmd = new SqlDataAdapter(sqlcmd,mycon);
DataSet ds = new DataSet();
mycmd.Fill(ds,"mytable");
StringWriter sw=new StringWriter();
sw.WriteLine("姓名\t班级\t学号\t学科\t成绩\t阶段\t日期\tID");
foreach(DataRow dr in ds.Tables["mytable"].Rows)
{
sw.WriteLine(dr[0].ToString()+"\t"+dr[1].ToString()+"\t"+dr[2].ToString()+"\t"+dr[3].ToString()+"\t"+dr[4].ToString()+"\t"+dr[5].ToString()+"\t"+dr[6].ToString()+"\t"+dr[7].ToString()+"\t");
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=MyExcel.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();