C#中怎么把数据库中的数据导出到excel
2个回答
展开全部
protected void btnSubmit_Click(object sender, EventArgs e)
{
sh();
}
void sh()
{
StringWriter sw = new StringWriter();
sw.WriteLine("商品Id\t商品名称<BR>");
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=ExeclTextDB;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from goods", conn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
sw.WriteLine(reader["goodsId"].ToString() + "\t" + reader["goodsName"].ToString() + "\t");
}
reader.Close();
conn.Close();
Response.Charset = "GB2312";
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("呵呵", System.Text.Encoding.UTF8) + "test.xls");//这句话是保存的Excel文件名
Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\"><title>显示详细信息</title></head><body>");
Response.Write(sw.ToString());
Response.Write("</body></html>");
Response.End();
sw.Close();
}
这个我做的一个例子 你自己看看咯 ...
{
sh();
}
void sh()
{
StringWriter sw = new StringWriter();
sw.WriteLine("商品Id\t商品名称<BR>");
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=ExeclTextDB;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from goods", conn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
sw.WriteLine(reader["goodsId"].ToString() + "\t" + reader["goodsName"].ToString() + "\t");
}
reader.Close();
conn.Close();
Response.Charset = "GB2312";
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("呵呵", System.Text.Encoding.UTF8) + "test.xls");//这句话是保存的Excel文件名
Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\"><title>显示详细信息</title></head><body>");
Response.Write(sw.ToString());
Response.Write("</body></html>");
Response.End();
sw.Close();
}
这个我做的一个例子 你自己看看咯 ...
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询