Search code examples
c#asp.net-mvc-5linq-to-excelexcel-import

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. 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!? Why not with the .xlsx ?


Solution

  • Unfortunately I needed to find a solution to this and as I did not get any help around this(i.e Replies and other posts), I had to make a decision and scrapped the above and only allowed importing of csv files.