c# 批量導入Excel數據到數據庫,根據兩個字段比對List取不重複的數據。

前臺代碼:

html:

<div class="panel panel-primary" style="max-width:400px;float:left;margin-left:20px;">
    <div class="panel-heading">
        <span class="glyphicon glyphicon-bullhorn" aria-hidden="true"></span>
        密度導入
    </div>
    <form id="frm" name="frm" method="post" style="margin-top:18px;">
        <input type="file" class="file" name="density" data-show-upload="false" data-show-delete="false" />
    </form>
    <label id="beforeSucc"></label>
    <hr/>
    <div style="position:relative;margin:5px;margin-right:10px!important;width:auto;margin-left:auto;text-align:right;">
        <a class="btn btn-danger" data-toggle="modal"  id="FrmBtn" >導入</a>
        @*<a class="btn btn-primary" onclick="document.execCommand('Refresh')">刷新</a>*@
    </div>

</div>
js:

        $('#FrmBtn').click(function(){
            $.ajax({
                url:'/Params/DensityIn',
                type:'POST',
                contentType: false,
                processData: false,
                data: new FormData($('#frm')[0]),
                beforeSend: function(){
                    $('#beforeSucc').text('正在導入,請稍後...');
                },
                success:function(data){
                    if (data=="導入成功") {
                        alert("導入成功!");

                    }
                    if (data=="文件讀取失敗") {
                        alert("文件讀取失敗!");
                    }
                    if (data=="提交了重複數據") {
                        alert("提交了重複數據!");
                    }
                    $('#beforeSucc').hide();
                },
                error:function(){
                    alert("error");
                }
            })
        
        });


 

後臺代碼:

//密度上傳
        public JsonResult DensityIn() 
        {
            if (Request.Files.Count>0)
            {
                HttpPostedFileBase file = Request.Files[0];
                var fileName = file.FileName;
                string filePath = "/UpLoad/MD/" + fileName;
                string AbsolutePath = Server.MapPath(filePath);
                file.SaveAs(AbsolutePath);

               //讀取excel數據
                var datableData = ExcelToDataTable(AbsolutePath);
                //excel數據轉換爲list
                var list = CommonTransafer.ToList<YLGL_MDHS>(datableData);
                //數據庫數據
                var mdList = (from a in db.YLGL_MDHS
                              select a).ToList();
                //獲取不重複數據
                var exp = list.Where(a => (!mdList.Exists(t => a.MDHS_SMD.Equals(t.MDHS_SMD) && a.MDHS_WD.Equals(t.MDHS_WD)))).Distinct().ToList();              
                var insert = new YLGL_MDHS() { };
                if (exp.Count() > 0)
                {
                    foreach (var item in exp)
                {
                    insert.MDHS_WD = item.MDHS_WD;
                    insert.MDHS_SMD = item.MDHS_SMD;
                    insert.MDHS_BMD = item.MDHS_BMD;
                    db.YLGL_MDHS.Add(insert);
                }
                db.SaveChanges();
                return Json("導入成功");  
                }
                else
                {
                    return Json("提交了重複數據");  
                }
            }
            return Json("文件讀取失敗");
        }


        /// <summary>
        /// DataTable 轉換爲List 集合
        /// </summary>
        /// <typeparam name="TResult">類型</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>

        
        public static DataTable ExcelToDataTable(string filePath)
        {
            try
            {
                DataTable dt = new DataTable();
                using (FileStream fs = new FileStream(filePath, FileMode.Open))
                {
                    string fileExt = Path.GetExtension(filePath);
                    IWorkbook workbook = null;
                    if (fileExt == ".xls")
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    else if (fileExt == ".xlsx")
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    ISheet sheet = workbook.GetSheetAt(0);
                    int rfirst = sheet.FirstRowNum;
                    int rlast = sheet.LastRowNum;
                    IRow row = sheet.GetRow(rfirst);
                    int cfirst = row.FirstCellNum;
                    int clast = row.LastCellNum;
                    for (int i = cfirst; i < clast; i++)
                    {
                        if (row.GetCell(i) != null)
                            dt.Columns.Add(row.GetCell(i).StringCellValue, System.Type.GetType("System.String"));
                    }
                    row = null;
                    for (int i = rfirst + 1; i <= rlast; i++)
                    {
                        DataRow r = dt.NewRow();
                        IRow ir = sheet.GetRow(i);
                        for (int j = cfirst; j < clast; j++)
                        {
                            if (ir.GetCell(j) != null)
                            {
                                r[j] = ir.GetCell(j).ToString();
                            }
                        }
                        dt.Rows.Add(r);
                        ir = null;
                        r = null;
                    }
                    sheet = null;
                    workbook = null;
                }
                return dt;
            }
            catch (Exception)
            {

                throw;
            }

        }





類CommonTransafer:

        /// <summary>
        /// DataTable 轉換爲List 集合
        /// </summary>
        /// <typeparam name="TResult">類型</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable dt) where T : class, new()
        {
            //創建一個屬性的列表
            List<PropertyInfo> prlist = new List<PropertyInfo>();
            //獲取TResult的類型實例  反射的入口
            Type t = typeof(T);
            //獲得TResult 的所有的Public 屬性 並找出TResult屬性和DataTable的列名稱相同的屬性(PropertyInfo) 並加入到屬性列表
            Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
            //創建返回的集合
            List<T> oblist = new List<T>();

            foreach (DataRow row in dt.Rows)
            {
                //創建TResult的實例
                T ob = new T();
                //找到對應的數據  並賦值
                prlist.ForEach(p =>
                {
                    try
                    {
                        if (row[p.Name] != DBNull.Value)
                        {
                            object obj = row[p.Name];
                            PropertyInfo ptyInfo = ob.GetType().GetProperty(p.Name);
                            Type coltyp = ptyInfo.PropertyType;
                            if (coltyp.IsGenericType && coltyp.GetGenericTypeDefinition() == typeof(Nullable<>))
                            {
                                coltyp = coltyp.GetGenericArguments()[0];
                            }

                            if (p.Name.Equals("DepartmentId") || p.Name.Equals("CardTypeId"))
                                p.SetValue(ob, Convert.ToInt32(obj.ToString().Trim()), null);
                            else
                                p.SetValue(
                                ob,
                                Convert.ChangeType(obj, coltyp),
                                null);
                        }
                    }
                    catch (Exception)
                    {


                    }
                });
                //放入到返回的集合中.
                oblist.Add(ob);
            }
            return oblist;
        }

 

截圖:

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章