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