~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
开发工具与关键技术:VS、读取Excel表格的数据
作者:#33
撰写时间:撰写时间:2019年05月11日
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
在老师MVC教学中学习关于读取Excel表格的数据并显示在视图页面的知识,在Excel中创建一个导入模板,
创建Excel表格的头部名字要对应渲染的表格!如下列的下载的模板格式。
下面就是数据读取成功的图片:点击批量导入员工按钮进入表格渲染好弹出层
function openEmployeeExcel() {$("#frmExcelData input[type='reset']").click();//重置
$("#modExcelData").modal();// 弹出层tabEmpExcel.reload();//刷新表格 }
控制器方法:获取文件类型,定义为二进制数组,然后读取该文件内容;查询员工信息,将数据存放进datatab中;通过foreach遍历循环datatab的数据(创建一个类获取需要的字段),将数据添加到实例化的表中。再将数据储存在储存到Session中,并return回视图。
public ActionResult ImportExcel(HttpPostedFileBase file) { ReturnJson msg = new ReturnJson(); try{//文件类型 string fileExtension = Path.GetExtension(file.FileName).ToLower(); if (".xls".Equals(fileExtension)) {//判断是否是该文件类型 byte[] fileBytes = new byte[file.ContentLength];//定义二进制数组 file.InputStream.Read(fileBytes, 0, file.ContentLength);//读取文件内容 if (ExcelReader.HasData(new MemoryStream(fileBytes))) //判断是否为空{ //查询员工信息 List<PW_Employee> tbemployee = myModel.PW_Employee.ToList(); List<EmployeeInforess> listemployee = new List<EmployeeInforess>(); //获取 Excel的数据,放进DataTable中 DataTable dtexcel = ExcelReader.RenderFromExcel(new MemoryStream(fileBytes), 0, 0); foreach (DataRow row in dtexcel.Rows) //遍历datatable 获取数据{ EmployeeInforess employee = new EmployeeInforess();//实例化 try{//员工ID 与员工名称 employee.employeeID = tbemployee.Where(m => m.employeeID == employee.employeeID && m.employeeName == row["员工姓名"].ToString().Trim()).SingleOrDefault().employeeID; employee.employeeName = row["员工姓名"].ToString().Trim(); employee.employeeNum = row["员工编号"].ToString().Trim(); employee.telphone = row["联系电话"].ToString().Trim(); employee.address = row["家庭地址"].ToString().Trim(); listemployee.Add(employee); } catch (Exception e) { msg.Text = "表格数据读取异常!";} } msg.State = true; msg.Text = "数据读取成功!"; Session["ExcelFile"] = listemployee; } else{ msg.Text = "该Excel文件为空!";} }}catch (Exception e) { Console.WriteLine(e); msg.Text = "数据异常!";} return Json(msg, JsonRequestBehavior.AllowGet); } |
将保存在Session中的Excel需要导入的员工数据查询出来:
public ActionResult SelectImportEmployee(LayuiTablePage layuiTablePage) { try { List<EmployeeInforess> listEmployee = new List<EmployeeInforess>(); if (Session["ExcelFile"] != null) { listEmployee = Session["ExcelFile"] as List<EmployeeInforess>; } int totalRow = listEmployee.Count(); listEmployee = listEmployee.OrderBy(m => m.employeeID). Skip(layuiTablePage.GetStartIndex()).Take(layuiTablePage.limit).ToList(); LayuiTableData<EmployeeInforess> layuiTableData=newLayuiTableData<EmployeeInforess>() {count = totalRow, data = listEmployee}; return Json(layuiTableData, JsonRequestBehavior.AllowGet); } catch (Exception) {return Json("", JsonRequestBehavior.AllowGet); }} |
视图中的方法:点击选择文件按钮(上图绿色框)获取文件(input类型为file文件类型),同时触发选项Excel文件按钮改变事件。
<input type="reset" name="reset" value="" hidden />//隐藏域—重置 <input type="file" name="file" accept=".xls" value="dd" onchange="upExcel()"> |
function upExcel() {//选择Excel文件按钮值的改变事件 var formData = new FormData(document.getElementById("frmExcelData"));//表单 var xhr; if (window.XMLHttpRequest) {xhr = new XMLHttpRequest();}//创建对象XMLHttpRequest对象 else {//老版本使用ActiveXObject对象 xhr = new ActiveXObject("Microsoft.XMLHTTP");} xhr.open("POST", "/Main/ImportExcel");//向服务器发送请求(提交类型post)/url xhr.send(formData); //将请求发送到服务器(提交数据) xhr.onreadystatechange = function () {//onreadystatechange事件 //XMLHttpRequest状态:4=请求已完成,且响应已就绪;200:(OK) if (xhr.readystate == 4 && xhr.status == 200) { if (xhr.responsetext) { var obj = JSON.parse(xhr.responseText); if (obj.state) { layer.alert(obj.text, { icon: 3, offset: '100px' }); tabEmpExcel = layuitable.reload("tabEmpExcel", { url: "/Main/SelectImportEmployee"});//表格重载 }else{layer.alert(obj.text, { icon: 3, offset: '100px' }); } }}}} |