private void Toexcel()
{
//获取数据集
SqlConnection conn=new SqlConnection("连接数据库");
string strsql="select * from student";
SqlDataAdapter da=new SqlDataAdapter(strsql,conn);
DataSet ds=new DataSet();
da.Fill(ds,"test");
DataTable dt=ds.Tables["test"];
StringWriter sw=new StringWriter(); //创建对象
sw.WriteLine("学生信息"); //输入标题
sw.WriteLine("姓名/t年龄/t性别);//输入字段
//输入表格内容
foreach(DataRow dr in dt.Rows)
{
string str=dr["test"].ToString().Replace("/r"," ");
sw.WriteLine(dr["姓名"]+"/t"+dr["年龄"]+"/t"+dr["性别"]);
}
sw.Close(); //关闭数据流
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls"); //test.xls导入Excel得文件名
Response.ContentType = "application/ms-excel";
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();
}
{
//获取数据集
SqlConnection conn=new SqlConnection("连接数据库");
string strsql="select * from student";
SqlDataAdapter da=new SqlDataAdapter(strsql,conn);
DataSet ds=new DataSet();
da.Fill(ds,"test");
DataTable dt=ds.Tables["test"];
StringWriter sw=new StringWriter(); //创建对象
sw.WriteLine("学生信息"); //输入标题
sw.WriteLine("姓名/t年龄/t性别);//输入字段
//输入表格内容
foreach(DataRow dr in dt.Rows)
{
string str=dr["test"].ToString().Replace("/r"," ");
sw.WriteLine(dr["姓名"]+"/t"+dr["年龄"]+"/t"+dr["性别"]);
}
sw.Close(); //关闭数据流
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls"); //test.xls导入Excel得文件名
Response.ContentType = "application/ms-excel";
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();
}