简体   繁体   English

导入Excel数据(使用LinqToExcel)仅在工作表打开的情况下有效C#MVC

[英]Importing Excel Data(using LinqToExcel) Only works If worksheet is open C# MVC

I am importing excel data into my DB, which works perfectly fine, but only if the spreadsheet is open. 我正在将excel数据导入到我的数据库中,该数据可以很好地工作,但前提是必须打开电子表格。 If it is not open, it gives an error of "Expected table not in correct format", any ideas why ? 如果未打开,则会显示错误消息“预期表格式不正确”,为什么? Thanks in advance for any help! 在此先感谢您的帮助!

[HttpPost]
    public ActionResult ImportExcel(PipelineDetails model, HttpPostedFileBase FileUpload, int ProjectID)
    {
        string Result = "";

        if (FileUpload != null)
        {
            if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                string filename = FileUpload.FileName;
                string pathToExcelFile = filename;

                var excelFile = new ExcelQueryFactory();
                excelFile.FileName = pathToExcelFile;

                excelFile.AddMapping<PipelineDetails>(x => x.Accumulated_Length, "Accumulated Length");
                excelFile.AddMapping<PipelineDetails>(x => x.Elevation, "Elevation");
                excelFile.AddMapping<PipelineDetails>(x => x.Pipe_Outside_Diameter, "Pipe Outside Diameter");
                excelFile.AddMapping<PipelineDetails>(x => x.Wall_Thickness, "Wall Thickness");
                excelFile.AddMapping<PipelineDetails>(x => x.Control_Point_Description, "Control Point Description");
                excelFile.AddMapping<PipelineDetails>(x => x.Control_Point_Size, "Control Point Size");

                var pipelineData = from PLD in excelFile.Worksheet<PipelineDetails>() select PLD;

                try
                {
                    foreach (var a in pipelineData)
                    {
                        if (a.Accumulated_Length == null || a.Elevation == null || a.Pipe_Outside_Diameter == null ||
                                a.Wall_Thickness == null)
                        {
                            Result = "There is a problem with the Import File. Please check the file format or data.";
                            return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
                        }
                    }
                }
                catch (Exception ex)
                {
                    Result = "There is a problem with the Import File. Please check the file format or data.";
                    return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
                }


                ProjectManager PM = new ProjectManager();
                PM.DeleteALLPipeLine_forProject(ProjectID);

                foreach (var a in pipelineData)
                {
                    try
                    {
                        if (a.Accumulated_Length.ToString() != "" && a.Elevation.ToString() != "" && a.Pipe_Outside_Diameter.ToString() != "" && 
                            a.Wall_Thickness.ToString() != "")
                        {
                            using (RexusTradingEntities RTE = new RexusTradingEntities())
                            {
                                PipelineData PD = new PipelineData();
                                PD.Accumulated_Length = Convert.ToDecimal(a.Accumulated_Length);
                                PD.Elevation = Convert.ToDecimal(a.Elevation);
                                PD.Pipe_Outside_Diameter = Convert.ToDecimal(a.Pipe_Outside_Diameter);
                                PD.Wall_Thickness = Convert.ToDecimal(a.Wall_Thickness);
                                PD.Control_Point_Description = a.Control_Point_Description;
                                PD.Control_Point_Size = a.Control_Point_Size;
                                PD.fkiProjectID = ProjectID;
                                PD.CreateDateTimeStamp = DateTime.Now;

                                RTE.PipelineDatas.Add(PD);
                                RTE.SaveChanges();
                            }
                        }
                    }

                    catch (DbEntityValidationException ex)
                    {
                        foreach (var entityValidationErrors in ex.EntityValidationErrors)
                        {

                            foreach (var validationError in entityValidationErrors.ValidationErrors)
                            {

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

                            }

                        }
                    }
                }

                //Adding the Node Numbers in sequencial order
                PM.UpdatePipelineNodeNumbers(ProjectID, model);

                Result = "Import Success";

                return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
            }
            else
            {
                Result = "Only Excel file format is allowed.";
                return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
            }
        }
        else
        {
            Result = "No Import File Selected.";
            return RedirectToAction("Index", "Pipeline", new { id = ProjectID, result = Result });
        }
    }

EDIT: I have also tried adding the following, but still get the error : 编辑:我也尝试添加以下内容,但仍然收到错误:

if (FileUpload.FileName.EndsWith("xlsx"))
                {
                    excelFile.DatabaseEngine = LinqToExcel.Domain.DatabaseEngine.Ace;
                }

if (FileUpload.FileName.EndsWith("xls"))
                {
                    excelFile.DatabaseEngine = LinqToExcel.Domain.DatabaseEngine.Jet;
                }

EDIT: I just saved my .xlsx file as .xls and it imported perfect!? 编辑:我只是将我的.xlsx文件另存为.xls,并且它导入了完美的!? Why not with the .xlsx ? 为什么不使用.xlsx?

不幸的是,我需要找到解决方案,并且由于没有任何帮助(例如,答复和其他帖子),我不得不做出决定并取消上面的操作,只允许导入csv文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM