建议你去下载一个动网的通用类库。
在下面的命名空间里面,Maticsoft.Common.DataConversion
调用方法
public string DataTableToExcel(System.Data.DataTable dt, string excelPath)。
你先从sql里面讲数据读到datatable,一个函数指定一个路径,就能得到excel文件了。
这个是目前,我发现的最简单的办法。
protected void btnSubmit_Click(object sender, EventArgs e)
{
StringWriter sw = new StringWriter();
sw.WriteLine("商品Id\t商品名称
");
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();
while (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("