public ActionResult AddBooks(ManageBooksViewModel manageBooksViewModel) { if (manageBooksViewModel == null) { return View("~/Views/Common/NotFound.cshtml", new NotFoundViewModel() {ElementName = "Books"}); } if (ModelState.IsValid) { ReadExcelSchemaAndCreateBooks(manageBooksViewModel); if (ModelState.Values.Any(x => x.Errors.Count >= 1)) { return View("AddMany", manageBooksViewModel); } } else { ModelState.AddModelError(string.Empty, "Please upload an Excel file with book information."); return View("AddMany", manageBooksViewModel); } return RedirectToAction("index"); }
private void ReadExcelSchemaAndCreateBooks(ManageBooksViewModel manageBooksViewModel) { try { var fileName = manageBooksViewModel.ExcelSchemaBase.FileName; if (_fileFormatValidation.IsExcelType(fileName)) { var filePath = SaveOnServer(manageBooksViewModel.ExcelSchemaBase.FileName, Keys.ExcelSchemaBase); var excelSchema = new FileInfo(filePath); var datafile = new ExcelPackage(excelSchema); var workbook = datafile.Workbook; var workSheet = workbook.Worksheets.First(); const int startRowIndex = 2; for (var rowIndex = startRowIndex; rowIndex <= workSheet.Dimension.End.Row; rowIndex++) { var book = ExtractValuesFromWorksheetAndCreateBook(workSheet, rowIndex); if (book != null) { _bookService.Add(book); } } } else { ModelState.AddModelError(string.Empty, "Please upload a valid Excel document."); } } catch (Exception e) { ModelState.AddModelError(string.Empty, "Something was wrong with the upload, please make sure the Excel template is correctly defined."); _logger.Error(e); } }