MVC中Excel上传并显示,插入到数据库
总体思路:上传文件->由office接口,select *from得到数据源dt->显示到页面->删除单个数据->更新数据源->用事务导入到数据库
上传文件:这里以MVC为例。
view里的文件:上传文件的代码,上传到控制器:SystemAdminContronllers.cs,方法actionname名:GetExcelFile
这里不一定按照笔主的上传书写,只要确定上传了文件即可
1 @using (Html.BeginForm("GetExcelFile", "SystemAdmin", FormMethod.Post, new { id="theForm", enctype = "multipart/form-data" }))
2 {
3 <input id="file" name="uploadFile" type="file"/>
4 <button class="btn btn-default" id="btnup" type="submit">上传</button>
5 }
控制器中的SystemAdminContronllers.cs中的GetExcelFile内容:
1 //上传Excel文件,且保存到指定文件夹
2 [HttpPost]
3 public ActionResult GetExcelFile(HttpPostedFileBase uploadFile)
4 {
5 string FileName;
6 string savePath;
7
8 if (uploadFile != null && uploadFile.ContentLength > 0)
9 {
10 string filename = Path.GetFileName(uploadFile.FileName);
11 int filesize = uploadFile.ContentLength;//得到上传文件字节byte大小
12 string NoFileName = Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
13 string fileEx = Path.GetExtension(filename);//得到扩展名
14
15 int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
16 string FileType = ".xls,.xlsx";//定义上传文件的类型字符串
17
18 //原文件名加上上传的日期
19 FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
20
21 //上传的日期做文件名
22 //FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
23
24 //判断是否格式正确
25 if (!FileType.Contains(fileEx))
26 {
27 ViewBag.error = "文件类型不对,只能导入xls和xlsx格式的文件";
28 return View();
29 }
30
31 //判断上传文件大大小
32 if (filesize >= Maxsize)
33 {
34 ViewBag.error = "上传文件超过4M,不能上传";
35 return View();
36 }
37
38 //确定文件的存放位置
39 string path = AppDomain.CurrentDomain.BaseDirectory + "Excel";
40 savePath = Path.Combine(path, FileName);//合成存放的路径
41
42 Session["filePath"] = savePath;
43
44 //保存操作
45 uploadFile.SaveAs(savePath);
46 }
47 else
48 {
49 return RedirectToAction("Index", "Error");
50 }
51 return View();
52 }
经过上面的操作后,该Excel文件已经保存到了服务器上。
下面说说得到数据源,也就是这篇文章,笔主认为最关键的地方
后台单独写一个函数,返回的是一个List<model>数据类型,这里解释一下,model里面包含你的数据
举个简单的例子 :这里是UserModel,那么应该返回的是 List<UserModel>
其他你想要的数据依次类推。
具体函数:
1 //得到初始数据源List 2 public List<UserInfoModel> GetUserInfoList() 3 { 4 string filePath = ""; 5 filePath = Session["filePath"].ToString(); 6 if(filePath != null) 7 { 8 List<UserInfoModel> list = new List<UserInfoModel>(); 9 try 10 { 11 //F:\\学习科目文档\\net综合课程设计\\课程设计图书管理系统\\MVCBaseFrame\\MVCBaseFrame.Web\\Excel\\test.xlsx 12 string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DBContext"].ToString(); 13 SqlConnection conn = new SqlConnection(strCon); 14 string sql = "select *FROM OPENROWSET('Microsoft.ace.OLEDB.12.0','Excel 12.0;HDR=YES;DATABASE="+filePath+"',Sheet1$)"; 15 conn.Open(); 16 SqlDataAdapter da = new SqlDataAdapter(sql, conn); 17 DataSet ds = new DataSet(); 18 da.Fill(ds); 19 conn.Close(); 20 DataTable dt = ds.Tables[0]; 21 22 if (dt != null) 23 { 24 for (int i = 0; i < dt.Rows.Count; i++) 25 { 26 UserInfoModel model = new UserInfoModel(); 27 model.UserId = dt.Rows[i]["UserId"].ToString(); 28 model.UserName = dt.Rows[i]["UserName"].ToString(); 29 model.Departments = dt.Rows[i]["Departments"].ToString(); 30 model.Major = dt.Rows[i]["Major"].ToString(); 31 model.Phone = dt.Rows[i]["Phone"].ToString(); 32 model.Email = dt.Rows[i]["Email"].ToString(); 33 model.Max = Convert.ToInt32(dt.Rows[i]["Max"].ToString()); 34 model.Time = Convert.ToInt32(dt.Rows[i]["Time"].ToString()); 35 list.Add(model); 36 } 37 return list; 38 } 39 return null; 40 } 41 catch 42 { 43 return null; 44 } 45 } 46 return null; 47 }
这里面最为关键的一句话为:
select *FROM OPENROWSET('Microsoft.ace.OLEDB.12.0','Excel 12.0;HDR=YES;DATABASE="+filePath+"',Sheet1$)
想平常查询SQL语句一样查询,只不过数据源是excel表。对于执行SQL语句查询后,得到一个DataTabel类型数据,大家应该不难理解,如果这部分不会,则是ADO.net数据库的基本操作不会。进行 相应的百度即可。
OPENROWSET关键字可以认为是office的excel软件提供给数据库查询的接口关键字,Microsoft.ace.OLEDB.12.0这个是excel的版本,笔主这里用的是offece2013,相应的其他版本,如2007时,则该成相应的版本。后面的database就是数据源的意思,Sheet1$代表的是表的左下角名字。
第一次发表,文笔不佳,书写有误,敬请指出。

浙公网安备 33010602011771号