【问题标题】:Import Excel Data to Multiple Tables in SQL Server Database using MVC C#使用 MVC C# 将 Excel 数据导入 SQL Server 数据库中的多个表
【发布时间】:2020-09-09 16:48:15
【问题描述】:

我有两个表(qf_schoolQuestionqf_schoolOptionqf_schoolOption 表的外键为 questionId,这是 qf_schoolQuestion 表中的主键。

TABLES:
qf_schoolQuestion | qf_schoolOption
----------------------------------
questionId        | schoolOptionId
questionTitle     | questionId
etc columns       | firstChoice
                  | secondChoice
                  | thirdChoice
                  | fourthChoice

我想将 Excel 数据批量插入两个表,但问题是我的代码会在两个表中插入记录,但是当数据插入 qf_schoolQuestion 时,它会插入所有数据,但是当它在另一个表中插入记录时表即qf_schoolOption 然后出现问题...

问题是假设我们在excel表中有两条记录然后在f_schoolQuestion表中插入的数据显示两条记录有两个生成的主键,但是当数据插入到另一个表中时,即qf_schoolOption表它会输入4记录到sql server, 假设 id 是由qf_schoolQuestion 生成的表是 '2044'、'2045',那么qf_schoolOption 表将插入从 excel 表中选择的两行到 '2044' id 和 '2045' id 的两条记录。

HttpPost:

        public JsonResult SchoolQuesImport(HttpPostedFileBase fileUpload)
        {
            List<string> data = new List<string>();
            if (fileUpload != null)
            {
                if (fileUpload.ContentType == "application/vnd.ms-excel" || fileUpload.ContentType == "application/octet-stream" || fileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    string filename = fileUpload.FileName;
                    string targetpath = Server.MapPath("~/UploadContent/");
                    fileUpload.SaveAs(targetpath + filename);
                    string pathToExcelFile = targetpath + filename;
                    var connectionString = "";

                    if (filename.EndsWith(".xls"))
                    {
                        connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0; HDR=YES", 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);
                    }
                    //"Xml;HDR=YES;IMEX=1\";
                    var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
                    var ds = new DataSet();

                    adapter.Fill(ds, "ExcelTable");

                    DataTable dtable = ds.Tables["ExcelTable"];

                    string sheetName = "Sheet1";

                    var excelFile = new ExcelQueryFactory(pathToExcelFile);

                    var artistAlbums = from a in excelFile.Worksheet<qf_schoolQuestion>(sheetName) select a;
                    var parentartistalbum = from b in excelFile.Worksheet<qf_schoolOption>(sheetName) select b;

                    foreach (var a in artistAlbums)
                    {
                        try
                        {
                            if (a.questionTitle != "" && a.questionLevel != "" && a.questionLang != "")
                            {
                                qf_schoolQuestion sq = new qf_schoolQuestion();

                                #region School Question
                                //sq.questionId = a.questionId;
                                sq.examTypeId = a.examTypeId;
                                sq.examCategoryId = a.examCategoryId;
                                sq.examSubCategoryId = a.examSubCategoryId;
                                sq.examSubjectId = a.examSubjectId;
                                sq.questionLang = a.questionLang;
                                sq.questionLevel = a.questionLevel;
                                sq.questionRefBook = a.questionRefBook;
                                sq.questionTitle = a.questionTitle;
                                sq.questionYear = a.questionYear;
                                sq.createdDate = DateTime.Now;
                                sq.createdBy = User.Identity.Name;

                                #endregion
                                context.qf_schoolQuestion.Add(sq);
                                context.SaveChanges();

                                foreach (var b in parentartistalbum)
                                {
                                    try
                                    {
                                        if (b.firstChoice != "")
                                        {
                                            qf_schoolOption so = new qf_schoolOption();

                                            #region School Options
                                            so.questionId = sq.questionId;
                                            so.firstChoice = b.firstChoice;
                                            so.secondChoice = b.secondChoice;
                                            so.thirdChoice = b.thirdChoice;
                                            so.fourthChoice = b.fourthChoice;

                                            #endregion
                                            context.qf_schoolOption.Add(so);
                                            context.SaveChanges();
                                        }
                                        else
                                        {
                                            data.Add("<ul>");
                                            if (b.firstChoice == "" || b.secondChoice == null) data.Add("<li>Choices are 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);
                                            }
                                        }
                                    }
                                }

                            }

                            else
                            {
                                data.Add("<ul>");
                                if (a.questionLang == "" || a.questionLang == null) data.Add("<li>Question Language 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);
                                }
                            }
                        }
                    }

                    //deleting excel file from folder  
                    if ((System.IO.File.Exists(pathToExcelFile)))
                    {
                        System.IO.File.Delete(pathToExcelFile);
                    }
                    return Json("success", JsonRequestBehavior.AllowGet);
                }
                else
                {
                    //alert message for invalid file format  
                    data.Add("Only Excel file format is allowed");
                    data.ToArray();
                    return Json(data, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                if (fileUpload == null) data.Add("Please choose Excel file");
                data.ToArray();
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }

【问题讨论】:

  • 有没有办法缩短你的代码?或者更具体地能够找到错误?
  • 您只需检查两个循环在另一个循环中运行一个,第二个循环将插入重复记录。

标签: c# sql-server asp.net-mvc import-from-excel


【解决方案1】:

老实说问题的描述不是很清楚,但我会尝试提出一个解决方案:在我看来,您首先必须在表qf_schoolQuestion中插入所有记录,然后再插入所有记录表qf_schoolOption;这样可以避免记录重复。

【讨论】:

  • 我的问题解决了
猜你喜欢
  • 1970-01-01
  • 2018-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多