上传读取Excel文件数据

本文介绍了一种通过上传Excel文件并将其数据读取到DataSet的方法。该过程涉及验证文件类型、保存文件、连接到Excel作为数据源并读取表结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1         /// <summary>
 2         /// 上传读取Excel文件数据
 3         /// 来自http://www.cnblogs.com/cielwater
 4         /// </summary>
 5         /// <param name="form"></param>
 6         /// <returns></returns>
 7         public ActionResult AreaExcelFile(FormCollection form)
 8         {
 9             HttpPostedFileBase fileField = Request.Files["fileField"];
10             string path = Server.MapPath("~/Excel");
11             if (!Directory.Exists(path))
12             {
13                 Directory.CreateDirectory(path);
14             }
15             string flieName = fileField.FileName;
16             string fileExt = Path.GetExtension(flieName).ToLower().Substring(1);
17             //验证是否为Excel文件
18             if (fileExt != "xls" && fileExt != "xlsx")
19             {
20                 ModelState.AddModelError("file", "您选择的不是Excel文件");
21                 return View("ExcelFile");
22             }
23             string FileName = path + flieName.Substring(flieName.LastIndexOf("\\"));
24             fileField.SaveAs(FileName);
25             //读取excel文件,转换成dataset
26             string strConn = "";
27             if (fileExt == "xls")
28             {
29                 strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=Excel 8.0;";
30             }
31             else if (fileExt == "xlsx")
32             {
33                 strConn = "Provider= Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
34             }
35             DataSet ds = new DataSet();
36             using (OleDbConnection conn = new OleDbConnection(strConn))
37             {
38                 conn.Open();
39                 //获取Excel表结构
40                 System.Data.DataTable sTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
41                 conn.Dispose();
42                 //遍历Excel文件所有表
43                 foreach (DataRow ExcelTable in sTable.Rows)
44                 {
45                     //读取表
46                     OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + ExcelTable[2] + "]", strConn);
47                     //写入DataSet
48                     oada.Fill(ds);
49                     //后面直接处理ds中的数据则可以
50                 }
51             }
52         }

 

转载于:https://www.cnblogs.com/CielWater/p/3580475.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值