~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
开发工具与关键技术:VS、Excel中的数据新增至数据库
作者:#33
撰写时间:撰写时间:2019年05月15日
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
在老师MVC教学中学习关于将Excel中的数据新增到数据库的知识,点击导入到数据库按钮将选择的数据模板新增入数据库。
控制器方法:定义两个int类型的变量分别用于记录保存成功的数据数量和已经存在的数据数据。查询保存在Session中的员工数据。
public ActionResult InsertImportEmployee(){ ReturnJson msg = new ReturnJson(); int savedCount = 0;//保存成功的条数 int oldCount = 0;//已经存在的数据条数 List<EmployeeInforess> listEmployee = new List<EmployeeInforess>(); if (Session["ExcelFile"] != null) {//判断Session中的数据是否为空 listEmployee = Session["ExcelFile"] as List<EmployeeInforess>;} if (listEmployee != null) { //遍历数据 foreach (EmployeeInforess Employee in listEmployee){ int count = (from tbEmployee in myModel.PW_Employee select tbEmployee).Count();//查询总条数 //保存员工 PW_Employee tbemployee = new PW_Employee(); tbemployee.employeeID = tbemployee.employeeID; tbemployee.employeeName = tbemployee.employeeName; tbemployee.employeeNum = tbemployee.employeeNum; tbemployee.telphone = tbemployee.telphone; tbemployee.address = tbemployee.address; myModel.PW_Employee.Add(tbemployee); savedCount += myModel.SaveChanges();。 oldCount++; } msg.State = true; //拼接返回的保存数据数量提示信息:导入总条数+已经存在条数+成功保存条数 msg.Text = "导入" + listEmployee.Count +"条数据,存在的数据有" + oldCount + "条,成功保存了" + savedCount + "条数据到数据库";} else{msg.Text = "数据为空!";} return Json(msg, JsonRequestBehavior.AllowGet); } |
视图方法:获取数据、提交数据、返回成功函数
////3.3 导入员工数据到数据库中 $("#ImportDatabase").click(function () { var trs = $(".modal-content .layui-table-body tr");//获取数据 if (trs.length > 0) { var layerIndex = layer.load(0);//显示加载层 $.ajax({//提交 type: "POST",//提交类型 url: "InsertImportEmployee",//提交路径 dataType: "json",//数据类型 success: function (message) { layer.close(layerIndex);//关闭加载层 layer.msg(message.Text, { icon: 0, skin: "layui-layer-molv" }); tabempSearch(); $("#modExcelData").modal('hide'); } });} else {layer.msg("没有符合要求的数据。", { icon: 0, skin: "layui-layer-molv" });} }); |