C# 如何用EXCEL存储数据。需要代码举例,谢谢

2024-11-08 23:39:54
推荐回答(1个)
回答(1):

方式很多,提供一种方式:直接使用ADO.net的OLEDB就可以连接Excel,和操作关系型数据库是一样的。
如:

将虚拟目录下的Temp作为临时文件目录。string urlPath = HttpContext.Current.Request.ApplicationPath + "/Temp/";string physicPath = HttpContext.Current.Server.MapPath(urlPath);string fileName = Guid.NewGuid() + ".Xls"; string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + physicPath + fileName +";Extended Properties=Excel 8.0;";OleDbConnection objConn = new OleDbConnection(connString);
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = objConn;建立表结构objCmd.CommandText = @"CREATE TABLE 客户信息
(
客户名 varchar,
注册时间 varchar
)
";objCmd.ExecuteNonQuery();插入新数据//建立插入动作的Command
objCmd.CommandText = "INSERT INTO 客户资料(客户名, 生日) VALUES (@CustomerName, @RegisterTime)";
objCmd.Parameters.Add(new OleDbParameter("@CustomerName", OleDbType.VarChar));
objCmd.Parameters.Add(new OleDbParameter("@RegisterTime", OleDbType.VarChar));
//遍历DataSet将数据插入新建的Excel文件中,customerInfo为我们从数据库中读到的数据
foreach (DataRow row in customerInfo.Tables[0].Rows)
{
for (int i=0; i
{
parm[i].Value = row[i];
}
objCmd.ExecuteNonQuery();
}
提供下载HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.WriteFile(path + fileName);
string httpHeader="attachment;filename=backup.Xls";
response.AppendHeader("Content-Disposition", httpHeader);
response.Flush();System.IO.File.Delete(path + fileName);//删除临时文件
response.End();