示例#1
0
        // leer archivo
        public ActionResult Import(HttpPostedFileBase excelfile, int?menu)
        {
            if (excelfile == null || excelfile.ContentLength == 0)
            {
                TempData["mensaje_error"] = "El archivo esta vacio o no es un archivo valido!";
                return(RedirectToAction("Index", "vlisnuevos", new { menu }));
            }
            //var buscaNombre = context.icb_arch_facturacion.FirstOrDefault(x => x.arch_fac_nombre == excelfile.FileName);

            //if (buscaNombre != null)
            //{
            //    TempData["mensajeError"] = "El nombre del archivo ya se encuentra registrado, verifique que el archivo no ha sido cargado antes o cambie de nombre!";
            //    return RedirectToAction("FacturacionGM", "gestionVhNuevo");
            //}

            //else
            //{
            if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx") ||
                excelfile.FileName.EndsWith("xlsm"))
            {
                string path = Server.MapPath("~/Content/" + excelfile.FileName);
                // Validacion para cuando el archivo esta en uso y no puede ser usado desde visual
                try
                {
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }

                    excelfile.SaveAs(path);
                }
                catch (IOException)
                {
                    TempData["mensaje_error"] =
                        "El archivo esta siendo usado por otro proceso, asegurece de cerrarlo o cree una copia del archivo e intente de nuevo!";
                    return(RedirectToAction("Index", "vlisnuevos", new { menu }));
                }


                ExcelPackage   Excel  = new ExcelPackage(new FileInfo(path));
                int            nows   = Excel.Workbook.Worksheets.Count;
                ExcelWorksheet range1 = Excel.Workbook.Worksheets["IMP ESPECIALES"];
                ExcelWorksheet range  = Excel.Workbook.Worksheets[1];


                // Read data from excel file
                //Excel.Application application = new Excel.Application();
                //Excel.Workbook workbook = application.Workbooks.Open(path);
                //Excel.Worksheet worksheet = workbook.ActiveSheet;
                //Excel.Range range = worksheet.UsedRange;


                //ArrayList arrText = new ArrayList();

                //var items = 0;
                int    itemsCorrectos = 0;
                int    itemsFallidos  = 0;
                string nombreArchivo  = excelfile.FileName;
                //items = range.Cells.[];
                //var num_porcentaje = Cells.Rows.Count / 10;

                //const string Query = "Delete from vlistanuevos";
                //context.Database.ExecuteSqlCommand(Query);
                List <listaCargaPreciosNuevosModel> listaCorrectos = new List <listaCargaPreciosNuevosModel>();
                List <listaCargaPreciosNuevosModel> listaErrado    = new List <listaCargaPreciosNuevosModel>();
                //var listaErrados = new List<vlistanuevos>();
                for (int row = 10; row <= 72; row++)
                {
                    try
                    {
                        decimal      Porcentajedescuento = 0;
                        vlistanuevos listanuevos         = new vlistanuevos();
                        int          lista       = Convert.ToInt32(range.Cells[row, 1].Value.ToString());
                        string       concepto    = range.Cells[row, 2].Text;
                        int          ano         = Convert.ToInt32(range.Cells[row, 3].Value.ToString());
                        int          mes         = Convert.ToInt32(range.Cells[row, 4].Value.ToString());
                        string       modelo      = range.Cells[row, 5].Text;
                        string       descripcion = range.Cells[row, 6].Text;
                        int          anomodelo   = Convert.ToInt32(range.Cells[row, 7].Value.ToString());
                        //var planmayor = range.Cells[row, 7].Text;
                        decimal preciolista     = Convert.ToDecimal(range.Cells[row, 8].Text.Replace("$", ""));
                        decimal precioespecial  = Convert.ToDecimal(range.Cells[row, 9].Text.Replace("$", ""));
                        decimal Preciodescuento = Convert.ToDecimal(range.Cells[row, 10].Text.Replace("$", ""));
                        try
                        {
                            Porcentajedescuento = Convert.ToDecimal(range.Cells[row, 11].Text.Replace("%", ""));
                        }
                        catch
                        {
                            Porcentajedescuento = Convert.ToDecimal(range.Cells[row, 11].Text.Replace("$", ""));
                        }

                        ObjectParameter output = new ObjectParameter("modeloInexistente", typeof(bool));

                        context.cargarListaNuevos(lista, concepto, ano, mes, modelo, descripcion, "", anomodelo,
                                                  preciolista, precioespecial, Preciodescuento, Porcentajedescuento, output);

                        bool salida = Convert.ToBoolean(output.Value);
                        if (!salida)
                        {
                            itemsCorrectos++;
                            listaCorrectos.Add(new listaCargaPreciosNuevosModel {
                                anio = anomodelo, modelo = modelo
                            });
                        }
                        else
                        {
                            itemsFallidos++;
                            //listaErrados.Add(new vlistanuevos { ano = anomodelo, descripcion = modelo });
                            listaErrado.Add(new listaCargaPreciosNuevosModel {
                                anio = anomodelo, modelo = modelo, mensaje = "El año modelo no existe."
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        itemsFallidos++;
                        TempData["mensaje_error"] =
                            "Error al leer archivo, revise que los campos no esten vacios o mal escritos, linea " +
                            (row + 1) + ex;
                        return(RedirectToAction("Index", "vlisnuevos", new { menu }));
                    }
                }
                //}

                try
                {
                    context.SaveChanges();
                    //    Excel.Close(0);
                    //Excel.Quit();
                    System.IO.File.Delete(path);
                }
                catch (DbEntityValidationException dbEx)
                {
                    Exception raise = dbEx;
                    foreach (DbEntityValidationResult validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (DbValidationError validationError in validationErrors.ValidationErrors)
                        {
                            string message = string.Format("{0}:{1}",
                                                           validationErrors.Entry.Entity,
                                                           validationError.ErrorMessage);
                            raise = new InvalidOperationException(message, raise);
                        }

                        TempData["mensaje_error"] = raise;
                        return(RedirectToAction("Index", "vlisnuevos", new { menu }));
                    }

                    throw raise;
                }
                catch (Exception ex)
                {
                    //workbook.Close(0);
                    //application.Quit();
                    System.IO.File.Delete(path);
                    TempData["mensaje_error"] = ex;
                    return(RedirectToAction("Index", "vlisnuevos", new { menu }));
                }
                TempData["correctos"]       = itemsCorrectos;
                TempData["fallidos"]        = itemsFallidos;
                TempData["listaNoCargados"] = listaErrado;
                TempData["listaCargados"]   = listaCorrectos;
                TempData["mensaje"]         = "La lectura del archivo se realizo correctamente!";
                return(RedirectToAction("Index", "vlisnuevos", new { menu }));
            }

            TempData["mensaje_error"] =
                "La lectura del archivo no fue correcta, verifique que selecciono un archivo valido.";
            return(RedirectToAction("Index", "vlisnuevos", new { menu }));
        }