public void ReadMoneyFile(MoneyFileUploadModels moneyFileUpload, SysUserModels userSession, string uploadFolder) { try { if (moneyFileUpload.moneyFile != null) { //... IExcelDataReader excelReader = null; if (moneyFileUpload.moneyFile.ContentType.Contains("ms-excel")) { //1. Reading from a binary Excel file ('97-2003 format; *.xls) excelReader = ExcelReaderFactory.CreateBinaryReader(moneyFileUpload.moneyFile.InputStream); } else { //2. Reading from a OpenXml Excel file (2007 format; *.xlsx) excelReader = ExcelReaderFactory.CreateOpenXmlReader(moneyFileUpload.moneyFile.InputStream); } //... //4. DataSet - Create column names from first row excelReader.IsFirstRowAsColumnNames = true; DataSet result = excelReader.AsDataSet(); DataTable dtData = result.Tables[0]; // Old ExcelIndexReaderUtils excelUtils = new ExcelIndexReaderUtils(); if (StringUtils.IsEmpty(moneyFileUpload.moneyFile.FileName)) { moneyFileUpload.errorMessage = Resource.MsgErrEmptyFile; return; } string errorMsg = string.Empty; IList<IdxIndexModels> indexList = excelUtils.GetMoneyFromExcel(dtData, this.mapper, out errorMsg); if (!StringUtils.IsEmpty(errorMsg)) { moneyFileUpload.errorMessage = errorMsg; } if (indexList != null) { // Save to db for (int i = 0; i < indexList.Count; i++) { IdxIndexModels index = indexList[i]; try { this.SaveMoney(index, userSession); } catch (Exception e) { Console.WriteLine(e.StackTrace); moneyFileUpload.errorMessage = e.Message; break; } } } //6. Free resources (IExcelDataReader is IDisposable) excelReader.Close(); } if (StringUtils.IsEmpty(moneyFileUpload.errorMessage)) { moneyFileUpload.infoMessage = Resource.MsgSuccess; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); //indexFileUpload.errorMessage = Resource.MsgErrUploadExcelFile; moneyFileUpload.errorMessage = ex.StackTrace; } }
public ActionResult UploadMoneyFile(MoneyFileUploadModels model) { SysUserModels userSession = (SysUserModels)Session["UserSession"]; IdxIndexDAO indexDAO = new IdxIndexDAO(this.mapper); model.moneyFile = Request.Files["moneyFile"]; string uploadFolder = Server.MapPath(Constants.File.UploadIndexFolder); indexDAO.ReadMoneyFile(model, userSession, uploadFolder); return View(model); }