上传读取Excel文件数据

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

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

发表评论

表情:
评论列表 (有 0 条评论,488人围观)

还没有评论,来说两句吧...

相关阅读