使用MVC C#将Excel数据导入SQL Server数据库中的多个表

问题描述

我有两个表(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中, 假设qf_schoolQuestion生成的ID为'2044','2045',则qf_schoolOption表将插入从Excel工作表到'2044'Id的双向行和'2045'ID的双向记录。 / p>

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);
            }
        }

解决方法

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