从excel文件更新sql表中的存在记录

时间:2017-04-01 13:00:24

标签: c# asp.net asp.net-mvc

我正在开发一个Web应用程序,其中我将外部文件中的记录导入,即Ms Excel到sql server数据库表我想检查sql表记录是否存在更新该记录否则从excel文件插入新记录 我正在使用asp.new mvc 5实体6 我的控制器代码是:

public JsonResult UploadExcel(Student student, HttpPostedFileBase FileUpload)
{
    List<string> data = new List<string>();
    if (FileUpload != null)
    {
        if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            string filename = FileUpload.FileName;
            string targetpath = Server.MapPath("~/Doc/");
            FileUpload.SaveAs(targetpath + filename);
            string pathToExcelFile = targetpath + filename;
            var connectionString = "";
            var ds = new DataSet();
            DataTable dtable = ds.Tables["ExcelTable"];
            string sheetName = "Sheet1";
            var excelFile = new ExcelQueryFactory(pathToExcelFile);
            var studentname = from a in excelFile.Worksheet<Student>(sheetName) select a;
            var artistAlbums = from a in excelFile.Worksheet<Student>(sheetName) select a;

            if (filename.EndsWith(".xls"))
            {
                connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
            }
            else if (filename.EndsWith(".xlsx"))
            {
                connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
            }
            var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
            adapter.Fill(ds, "ExcelTable");
            foreach (var a in artistAlbums)
            {
                try
                {
                    if (a.STUDENTNAME != "" && a.COURSEID != null && a.TEACHERID != null && a.PHOTOID != null)
                    {
                        Student TU = new Student();
                        TU.STUDENTID = a.STUDENTID;
                        TU.STUDENTNAME = a.STUDENTNAME;
                        TU.COURSEID = a.COURSEID;
                        TU.TEACHERID = a.TEACHERID;
                        TU.PHOTOID = a.PHOTOID;
                        db.Students.Add(TU);
                        db.SaveChanges();
                    }
                    else
                    {
                        data.Add("<ul>");
                        if (a.STUDENTNAME == "") data.Add("<li> Name is required</li>");
                        if (a.COURSEID == null) data.Add("<li> CourseId is required</li>");
                        if (a.TEACHERID == null) data.Add("<li> TeacherId is required</li>");
                        if (a.PHOTOID == null) data.Add("<li> PhotoId is required</li>");
                        data.Add("</ul>");
                        data.ToArray();
                        return Json(data, JsonRequestBehavior.AllowGet);
                    }
                }
                catch (DbEntityValidationException ex)
                {
                    foreach (var entityValidationErrors in ex.EntityValidationErrors)
                    {

                        foreach (var validationError in entityValidationErrors.ValidationErrors)
                        {

                            Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);

                        }
                    }
                }
            }
            if ((System.IO.File.Exists(pathToExcelFile)))
            {
                System.IO.File.Delete(pathToExcelFile);
            }
            return Json("success", JsonRequestBehavior.AllowGet);
        }
        else
        {
            data.Add("<ul>");
            data.Add("<li>Only Excel file format is allowed</li>");
            data.Add("</ul>");
            data.ToArray();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
    else
    {
        data.Add("<ul>");
        if (FileUpload == null) data.Add("<li>Please choose Excel file</li>");
        data.Add("</ul>");
        data.ToArray();
        return Json(data, JsonRequestBehavior.AllowGet);
    }
}           

1 个答案:

答案 0 :(得分:0)

if (a.STUDENTNAME != "" && a.COURSEID != null && a.TEACHERID != null && a.PHOTOID != null)
{
    var TU = db.Students.FirstOrDefault(p => p.STUDENTID == a.STUDENTID);
    if (TU != null)
    {
        TU.STUDENTNAME = a.STUDENTNAME;
        TU.COURSEID = a.COURSEID;
        TU.TEACHERID = a.TEACHERID;
        TU.PHOTOID = a.PHOTOID;
        db.Students.Update(TU);
    }
    else
    {
        TU = new Student();
        TU.STUDENTID = a.STUDENTID;
        TU.STUDENTNAME = a.STUDENTNAME;
        TU.COURSEID = a.COURSEID;
        TU.TEACHERID = a.TEACHERID;
        TU.PHOTOID = a.PHOTOID;
        db.Students.Add(TU);
    }

    db.SaveChanges();
}