Ejemplo n.º 1
0
        public IActionResult Post(IFormFile file)
        {
            if (file.Length > 0)
            {
                ISheet sheet;
                using (var stream = file.OpenReadStream())
                {
                    var sFileExtension = file.FileName.Split(".").Last();

                    if (string.IsNullOrEmpty(sFileExtension))
                    {
                        return(NotFound("No se encontro la extension del archivo"));
                    }

                    stream.Position = 0;
                    if (sFileExtension == "xls")
                    {
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }
                    else
                    {
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }

                    IRow headerRow     = sheet.GetRow(0); //Get Header Row
                    int  cellCount     = headerRow.LastCellNum;
                    var  tasasDeCambio = new List <TasaDeCambio>();
                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null)
                        {
                            continue;
                        }

                        if (row.Cells.All(d => d.CellType == CellType.Blank))
                        {
                            continue;
                        }

                        try
                        {
                            double   cambio = row.GetCell(1).NumericCellValue;
                            DateTime fecha  = row.GetCell(0).DateCellValue; //DateTime.ParseExact(row.GetCell(0).DateCellValue.Date.ToString(), "dd/MM/yyyy",
                            //Sy0stem.Globalization.CultureInfo.InvariantCulture);

                            tasasDeCambio.Add(new TasaDeCambio
                            {
                                Cambio = Convert.ToDouble(cambio),
                                Fecha  = fecha
                            });
                        }
                        catch (FormatException ex)
                        {
                            return(BadRequest($"Un error ocurrio " + ex.Message));
                        }
                    }

                    factory.InsertRange(tasasDeCambio);
                    factory.Save();
                }
            }


            return(Json(new
            {
                name = file.FileName,
                size = file.Length
            }));
        }