参考资料:http://www.cnblogs.com/jeffhsu/archive/2011/08/24/2152013.html
看了jeffhsu的方法挺好的,但需要做一个Excel模版,参考网上资料改进了一下。
//Asp.net 导出EXCEL
private void ExportExcel()
{
//临时文件
string tempFile = string.Format("{0}/{1}.xls", System.Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid());
//使用OleDb连接
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + tempFile + ";Extended Properties=Excel 8.0");
using (con)
{
con.Open();
//创建Sheet
OleDbCommand cmdCreate = new OleDbCommand("CREATE TABLE Sheet1 ([ID] VarChar,[名称] VarChar,[时间] VarChar)", con);
cmdCreate.ExecuteNonQuery();
//插入数据
OleDbCommand cmd = new OleDbCommand(@"INSERT INTO [Sheet1$] VALUES(@ID, @名称, @时间)", con);
cmd.Parameters.AddWithValue("@ID", "1");
cmd.Parameters.AddWithValue("@名称", "哈哈");
cmd.Parameters.AddWithValue("@时间", DateTime.Now);
cmd.ExecuteNonQuery();
}
Response.ContentType = "application/ms-excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=info.xls");
Response.BinaryWrite(File.ReadAllBytes(tempFile));
File.Delete(tempFile);
}
欢迎转载,转载请注明:转载自[ http://www.cnblogs.com/zjfree/ ]