ASP.NET中导入和导出标准Excel文件
时间:2010-12-18 来源:勤于思,敏于行
// 根据模板文件创建副本 string filePath = Server.MapPath("~/" + Guid.NewGuid().ToString() + ".xls"); File.Copy(Server.MapPath("~/demo.xls"), filePath); // 使用OleDb驱动程序连接到副本 OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0;"); using (conn) { conn.Open(); // 增加记录 OleDbCommand cmd = new OleDbCommand("INSERT INTO [Sheet1$]([ID], [姓名], [生日]) VALUES(@Id, @Name, @Birthday)", conn); cmd.Parameters.AddWithValue("@Id", "1"); cmd.Parameters.AddWithValue("@Name", "Hsu Yencheng"); cmd.Parameters.AddWithValue("@Birthday", "1981-10-13"); cmd.ExecuteNonQuery(); } // 输出副本的二进制字节流 Response.ContentType = "application/ms-excel"; Response.AppendHeader("Content-Disposition", "attachment;filename=info.xls"); Response.BinaryWrite(File.ReadAllBytes(filePath)); // 删除副本 File.Delete(filePath);
二、导入 相对于导出,导入部分的实现代码要简单的多:
string filePath = Server.MapPath("~/info.xls"); OleDbDataAdapter da = new OleDbDataAdapter( "SELECT * FROM [Sheet1$]", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0"); DataTable dt = new DataTable(); da.Fill(dt); // 接下来你就可以对 dt 为所欲为了……上面的代码中,我们导入了位于站点根目录的“info.xls”,导入时我们依旧使用OleDb驱动程序来访问Excel文件。再次提醒读者,此种方式只支持导入标准的Excel文件,这也是上面导出部分使用预先准备好的Excel模板文件的原因。 另外,以上演示仅针对Excel 2000-2003格式的文件,如果您要导入或导出的是Excel 2007文件(*.xlsx),那么您需要将连接字符串改为(可参考:http://www.connectionstrings.com/):
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=info.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";希望本文对您有所帮助。
相关阅读 更多 +
排行榜 更多 +