导入excel表格,保存到临时表

开发工具与关键技术:MVC
作者:文泽钦
撰写时间:2019年5月16日

上存excel表格前要判断要上存的文件是否为空,要上存的文件为空时直接返回return返回,若文件不为空则执行下一步。

//上存excel表格,保存到临时表
 function upExcel() {
  //避免取消选择文件后触发上存
  if ($("#fileUploadExecl").val() == "" || $("#fileUploadExecl").val == undefined){
            return;
        }
        var layIndex = layer.load();//显示加载层
        //提交表单
        $("#formImportExcel").ajaxSubmit(function (Msg) {
            layer.close(layIndex);//关闭加载层
            if (Msg.State) {
                //启用保存到数据库的按钮
                $("#btnSaveImport").prop("disabled", false);
                //表格数据重载
                tabEmployeeImport.reload({
                    url: "SelectSessImportEmployee"
                });
                layer.alert(Msg.Text, { icon: 1, title: "提示" });
            } else { //清空table
               tabEmployeeImport.reload({
                    url: '',
                    data: []});
                layer.alert(Msg.Text, { icon: 0, title: "提示" });}
       		 }); 
       	 }

将导入的excel表格数据保存到session的代码有点点多,用点心去看就会发现并不是那么复杂。

	public ActionResult ImportExcel(HttpPostedFileBase file) {
        ReturnJsonVo returnJson = new ReturnJsonVo();
       		 try
       		 {
            	//清除session中的ImportExcel残留数据
            	Session.Remove("ImportExcel");
            	
            	//判断页面传过来的文件是否为Excel表格
           		 //获取文件后缀名
            string fileExtension = System.IO.Path.GetExtension(file.FileName);//.xls
            
            if (".xls".Equals(fileExtension) || ".XLS".Equals(fileExtension))
             {
                //声明二进制数组存放文件
                byte[] fileBytes = new byte[file.ContentLength];
                
	 	 //将传入的文件转化为二进制的数组存入fileBytes
  		file.InputStream.Read(fileBytes, 0, file.ContentLength);
  		
 		 //将二进制的数组转化为内存流
  		 MemoryStream excelFileStream = new MemoryStream(fileBytes);
  		 
  		 //将内存流转化为工作簿,引入NPOI
   		 NPOI.SS.UserModel.IWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(excelFileStream);
   		 
		 //判断工作簿中是否有工作表
         if (workbook.NumberOfSheets > 0) 
         {
  			//查询部门、职位信息,用来根据名称获取对应的ID
  			List<SYS_Department> dbDepartment = (from tbDepartment in myModels.SYS_Department
                                       select tbDepartment).ToList();
 		    List<SYS_Position> dbPosition = (from tbPosition in myModels.SYS_Position
                                       select tbPosition).ToList();
                                       
      		 //声明对象列表,存放导入的学生信息
      		 List<employeeVo> listEmployeeVo = new List<employeeVo>();
      		 
      		 //获取第一个工作表
      		 NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(0);
      		 
     		 //PhysicalNumberOfRows 获取的是物理行数,也就是不包括那些空行(隔行)的情况。
     		 //判断工作表中是否有数据
                    if (sheet.PhysicalNumberOfRows > 0)
                     {
                        //将数据装到DataTable中
                        //定义DataTable
                        DataTable dtExcel = new DataTable();
                        //获取表题行
                        NPOI.SS.UserModel.IRow rowHeader = sheet.GetRow(0);
                        //获取表格列数
                        int cellCount = rowHeader.LastCellNum;
                        //获取表格行数(最后一行下标+1)
                        int rowCount = sheet.LastRowNum + 1;
                        
      //创建DataTable中的列,循环添加标题行各个单元格的数据
      for (int i = rowHeader.FirstCellNum; i < cellCount; i++)
       {
      //遍历表头行中每一个单元格,获取标题各个单元格的数据
      DataColumn dtColumn = new DataColumn(rowHeader.GetCell(i).StringCellValue);
      
       //将获取的标题行数据放到DataTable中
                   dtExcel.Columns.Add(dtColumn);
                   }
                   //获取excel中的数据
                   //(sheet.FirstRowNum)第一行是标题
                    for (int i = sheet.FirstRowNum + 1; i < rowCount; i++)
                     {
                   //获取行(1、2、3...)数据
                   NPOI.SS.UserModel.IRow row = sheet.GetRow(i);
                   
                   //创建DataTable行
                   DataRow dtRow = dtExcel.NewRow();
                   if (row != null)
                    {
                //遍历excel中一行所有的单元格
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
               		 if (row.GetCell(j) != null) 
               		 	{
                		 dtRow[j] = row.GetCell(j).ToString();
                                }}
                            //新行添加到DataTable中
                            dtExcel.Rows.Add(dtRow);
                            }
                         //声明变量,记录成功和失败数据的条数
        				 int ImportSuccess = 0;
        				 int ImportFail = 0;
        				 
                 //遍历DataTable中的数据
        	     foreach (DataRow row in dtExcel.Rows) 
        	     {
                 //创建employeeVo对象保存每一条数据
                  employeeVo employee = new employeeVo();
                  
         //捕获异常
         try
         {
         //获取部门id和部门名称
         //通过DataTable中的Department到dbDepartment中查找相应的Department
         employee.DeoartmentName = row["部门"].ToString().Trim();
         employee.DepartmentID = dbDepartment.Where(m => m.DeoartmentName == employee.DeoartmentName).SingleOrDefault().DepartmentID;
         
          //获取职位id和职位名称
          //根据职位id和职位名称获取相应的职位ID
          employee.PositionName = row["职位"].ToString().Trim();
          employee.PositionID = dbPosition.Where(m => m.PositionName == employee.PositionName).SingleOrDefault().PositionID;
          employee.EmployeeNumber = row["编号"].ToString().Trim();
          employee.EmployeeName = row["姓名"].ToString().Trim();
          employee.Phone = row["电话"].ToString().Trim();
          employee.Cellphone = row["手机"].ToString().Trim();
          employee.Address = row["地址"].ToString().Trim();
          
                  //将每一条数据都添加到对象列表中
                  listEmployeeVo.Add(employee);
                  ImportSuccess++;}
                     catch (Exception) {
                                returnJson.State = false;
                                returnJson.Text = "数据处理出错";
                                ImportFail++;
                                }
                      	    }
           //将数据保存到session中
           Session["ImportExcel"] = listEmployeeVo;
           returnJson.State = true;
           returnJson.Text = "Excel表格中一共有" + dtExcel.Rows.Count + "条数据,其中" + ImportSuccess + "条匹配成功,有" + ImportFail + "条匹配失败!";
           } else{
                        returnJson.State = false;
                        returnJson.Text = "数据表为空!";
                        }
                }else{
                    returnJson.State = false;
                    returnJson.Text = "工作簿中没有数据表!";}
            } else{
                returnJson.State = false;
                returnJson.Text = "文件类型错误,请上传Excel文件!";}
        }catch (Exception) {
            returnJson.State = false;
            returnJson.Text = "数据异常!";}
            return Json(returnJson, JsonRequestBehavior.AllowGet); 
        }

导入的控制器基本代码写完了,剩下的就是写保存到内存流的代码了,多看几遍或者多写几遍就会发现代码的结构都基本相同,唯有不同的只是命名了。
现在写分页操作,因为要考虑到导入excel表格的数据可能会比较多,要使用分页功能,分页的写法很简单,先提取session中的数据、进行分页操作。

public ActionResult SelectSessImportEmployee(LayuiTablePage layuiTablePage)
 {
        List<employeeVo> listStudentVo = new List<employeeVo>();
      		  if (Session["ImportExcel"] != null) 
        			{
            listStudentVo = Session["ImportExcel"] as List<employeeVo>;
            }
       		 //计算数据总条数
       		 int totalRow = listStudentVo.Count();
        	 List<employeeVo> listStu = listStudentVo
                     .OrderByDescending(m => m.EmployeeID)//根据学生id倒叙排序
                     .Skip(layuiTablePage.GetStartIndex())//分页
                     .Take(layuiTablePage.limit)//每页多少条数据
                     .ToList();
                     
     		//实例化
    	    LayuiTableData<employeeVo> layuiTableData = new LayuiTableData<employeeVo>();
       	    layuiTableData.count = totalRow;
            layuiTableData.data = listStu;
            return Json(layuiTableData, JsonRequestBehavior.AllowGet);
            }

启动看看是否能上存到session。
在这里插入图片描述
现在有两条数据匹配成功了,保存到数据库的方法没有写,现在只是临时保存到session中。
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值