zoukankan      html  css  js  c++  java
  • MVC下使用NPOI的Execl导入操作

    第一步

    首先导入NPOI引入文件(右键项目->管理NUget包,即可引入)

    第二步

    前台代码

    前台ajax代码

      yes: function (index) {    //点击确定回调事件
                            if (document.getElementById("fileDatass").value == null || document.getElementById("fileDatass").value == "") {
                                alert("请选择上传文件");
                                return;
                            } else {
                                var f_content = document.getElementById("fileData").value;//获取上传文件数据 //fileData是file标签id
                                var fileext = f_content.substring(f_content.lastIndexOf("."), f_content.length) //截取.后面文件类型
                                fileext = fileext.toLowerCase()
                                if (fileext != '.xls') { 
                                    alert("对不起,导入数据格式必须是xls格式文件哦,请您调整格式后重新上传,谢谢 !");
                                    o.file.focus();
                                    return;
                                } else {
                                   //获取表单数据
                                    var formData = new FormData($("#file-form")[0]) //根据表单ID获取表单数据
                                    $.ajax({
                                        type: "post", //必须post
                                        url: "ImportExcel", //控制器方法名
                                        data: formData,
                                        processData: false,
                                        contentType: false,
                                        success: function (data) {
                                            if (data == "导入失败、内容已有") {
                                                layer.msg("导入失败!专业名已有", { icon: 5 });
                                            } else if (data == "请选择有效的Execl文件") {
                                                layer.msg("请选择有效的Execl文件", { icon: 5 });
                                            } else if (data == "导入成功") {
                                                layer.msg("导入成功", { icon: 6 });
                                                //layui执行重载
                                                table.reload('demo', {
                                                    page: {
                                                        curr: usertable.curr //重新从记录 页开始
                                                    }
                                                });
                                                layer.close(index)//layui关闭弹出框
                                            } else if (data == "导入失败") {
                                                layer.msg("导入失败", { icon: 5 });
                                            } else {
                                                layer.msg("导入失败Execl文件,请联系开发人员", { icon: 5 });
                                            }
    
                                        }
                                    });
    
                                }
                            }
                        }
    

      第三步

    控制器方法

      1         /// <summary>
      2         /// Excel导入成Datable
      3         /// </summary>
      4         /// <param name="file">导入路径(包含文件名与扩展名)</param>
      5         /// <returns></returns>
      6         public ActionResult ImportExcel(HttpPostedFile fileData)
      7         {
      8           
      9             
     10             string iszq = "导入失败、内容已有";
     11             try
     12             {
     13                 HttpPostedFileBase file = Request.Files["fileData"];
     14                 if (file == null)
     15                 {
     16                     iszq = "请选择有效的Execl文件";
     17                     return Content(iszq, "text/plain"); 
     18                 }
     19                 //存入文件
     20                 if (file.ContentLength > 0)
     21                 {
     22                     //先存入在本地
     23                     file.SaveAs(Server.MapPath("~/UpFiles/DoxlFiles/") + System.IO.Path.GetFileName(file.FileName));
     24                 }
     25 
     26                 string a = Server.MapPath("~/UpFiles/DoxlFiles/" + file.FileName);
     27 
     28                 var datatable = ImportExcelFile(a);
     29 
     30                 
     31                 for (int i = 0; i < datatable.Rows.Count; i++)
     32                 {
     33                     if (!string.IsNullOrEmpty(datatable.Rows[i][0].ToString()))
     34                     {
     35                         //专业名查询数据库有没有重复
     36                       string subname  = datatable.Rows[i][0].ToString();
     37                         
     38                         //如果数据库已有当前列的专业名,就跳出循环,进行下一次循环
     39                             if (entity.subject.Where(p => p.subject_name == subname).Count() > 0)
     40                             {
     41                             continue;
     42                             }
     43                         
     44                         subject su = new subject();
     45                         //插入数据[0]是第一列
     46                         su.subject_name = datatable.Rows[i][0].ToString();
     47                         entity.subject.Add(su);
     48                         if (entity.SaveChanges() > 0)
     49                         {
     50                             iszq = "导入成功";
     51                         }
     52                         else
     53                         {
     54 
     55                             iszq = "导入失败";
     56                             break;
     57                         }
     58 
     59 
     60                     }
     61                 }
     62               
     63                 return Content(iszq, "text/plain");
     64             }
     65             catch (Exception)
     66             {
     67 
     68                 throw;
     69             }
     70         }
     71         /// <summary>
     72         /// Excel导入帮助类
     73         /// </summary>
     74         /// <param name="filePath"></param>
     75         /// <returns></returns>
     76         public DataTable ImportExcelFile(string filePath)
     77         {
     78             HSSFWorkbook hssfworkbook;
     79             #region//初始化信息
     80             try
     81             {
     82                 using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
     83                 {
     84                     hssfworkbook = new HSSFWorkbook(file);
     85                 }
     86             }
     87             catch (Exception e)
     88             {
     89                 throw e;
     90             }
     91             #endregion
     92 
     93             NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
     94             DataTable table = new DataTable();
     95             IRow headerRow = sheet.GetRow(0);//第一行为标题行
     96             int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
     97             int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
     98 
     99             //handling header.
    100             for (int i = headerRow.FirstCellNum; i < cellCount; i++)
    101             {
    102                 DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
    103                 table.Columns.Add(column);
    104             }
    105             for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
    106             {
    107                 IRow row = sheet.GetRow(i);
    108                 DataRow dataRow = table.NewRow();
    109 
    110                 if (row != null)
    111                 {
    112                     for (int j = row.FirstCellNum; j < cellCount; j++)
    113                     {
    114                         if (row.GetCell(j) != null)
    115                             dataRow[j] = (row.GetCell(j)).ToString();
    116                     }
    117                 }
    118 
    119                 table.Rows.Add(dataRow);
    120             }
    121             return table;
    122 
    123 
    124         }
  • 相关阅读:
    微信公众号教程(5)自动回复操作案例
    微信公众号教程(4)微信公众平台编辑模式介绍
    微信公众号教程(3)微信公众平台群发消息
    微信公众号教程(2)微信公众平台后台介绍
    微信公众号教程(1)微信公众账号注册、设置、登陆
    二级c程序设计题(2)
    二级c程序设计题(1)
    C++经典编程题#6:分配病房
    C++经典编程题#5:寻找下标
    python-----面向对象三大特性
  • 原文地址:https://www.cnblogs.com/wangshaod/p/10542229.html
Copyright © 2011-2022 走看看