public ActionResult Create(CreateTallySheetInput input, HttpPostedFileBase file) { if (ModelState.IsValid) { if (file != null && file.ContentLength > 0) { //ExcelDataReader works on binary excel file Stream stream = file.InputStream; //We need to written the Interface. IExcelDataReader reader = null; if (file.FileName.EndsWith(".xls")) { //reads the excel file with .xls extension reader = ExcelReaderFactory.CreateBinaryReader(stream); } else if (file.FileName.EndsWith(".xlsx")) { //reads excel file with .xlsx extension reader = ExcelReaderFactory.CreateOpenXmlReader(stream); } else { //Shows error if uploaded file is not Excel file ModelState.AddModelError("File", "This file format is not supported"); var specieCategories = _specieCategoryAppService.GetSpecieCategories().Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.Name }); ViewBag.SpecieCategoryId = specieCategories; return(View(input)); } //treats the first row of excel file as Coluymn Names reader.IsFirstRowAsColumnNames = true; //Adding reader data to DataSet() DataSet result = reader.AsDataSet(); reader.Close(); //Sending result data to database _tallySheetAppService.UploadTallySheet(input, result.Tables[0]); //return View(); } } else { ModelState.AddModelError("File", "Please upload your file"); } return(RedirectToAction("Create", new { id = input.PlotId })); }
public ActionResult Talling(int CompartmentId, int SpecieCategoryId, int TariffNumber, HttpPostedFileBase file) { try { if (file != null && file.ContentLength > 0) { //ExcelDataReader works on binary excel file Stream stream = file.InputStream; var reader = string.Equals(Path.GetExtension(file.FileName), ".xls") ? ExcelReaderFactory.CreateBinaryReader(stream) : ExcelReaderFactory.CreateOpenXmlReader(stream); int plotId; //Loop through data sheet do { while (reader.Read()) { CreatePlotInput input = new CreatePlotInput(); CreateTallySheetInput tallyInput = new CreateTallySheetInput(); input.CompartmentId = CompartmentId; input.Name = reader.Name; string name = reader.Name; plotId = _plotAppService.CreatePlot(input); tallyInput.PlotId = plotId; tallyInput.SpecieCategoryId = SpecieCategoryId; tallyInput.TariffNumber = TariffNumber; //treats the first row of excel file as Coluymn Names reader.IsFirstRowAsColumnNames = true; //Adding reader data to DataSet() DataSet result1 = reader.AsDataSet(); //Sending result data to database _tallySheetAppService.UploadTallySheet(tallyInput, result1.Tables[reader.Name]); reader.Close(); } } while (reader.NextResult()); return(RedirectToAction("Index")); } else { ModelState.AddModelError("File", "Please upload your file"); return(RedirectToAction("Index")); } } catch (Exception ex) { throw new Exception(ex.Message); } }