Introduction
There are many ways available to convert excel file to DataTable, I found this is the best approach to do so.
In your controller, you can add an action method UploadRewardsMembership(), which will read the excel file and convert the content into a data table. Then form the UploadRewardsMembership method, you can call the repository method InsertFCReward() to insert the data to the database.
- public ActionResult UploadRewardsMembership()
- {
- try
- {
- HttpPostedFileBase fileBase;
- DataTable dataTable = new DataTable();
- if(Request.Files.Count > 0)
- {
- foreach (string file in Request.Files)
- {
- fileBase = Request.Files[file] as HttpPostedFileBase;
- if (fileBase != null && fileBase.ContentLength > 0)
- {
- Stream stream = fileBase.InputStream;
- IExcelDataReader reader = null;
- if (fileBase.FileName.EndsWith(".xls"))
- {
- reader = ExcelReaderFactory.CreateBinaryReader(stream);
- }
- else if (fileBase.FileName.EndsWith(".xlsx"))
- {
- reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
- }
- var result = reader.AsDataSet(new ExcelDataSetConfiguration()
- {
- ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
- {
- UseHeaderRow = true
- }
- });
- dataTable = result.Tables[0];
- int resultCount = InsertFCReward(dataTable);
- if (resultCount == -1)
- {
- ViewBag.FCRewardMessage = fileBase.FileName + " is not in correct format.";
- break;
- }
- reader.Close();
- }
- }
- }
- else
- {
- ViewBag.FCRewardMessage = "Please select a file for upload.";
- }
- var admin = new Admin
- {
- Page = new AdminPage()
- {
- CurrentPage = 1,
- PageSize = 50,
- },
- };
- admin.RewardMemberships = GetRewardsMembershipDetails(admin.Page);
- return PartialView("_MembershipGrid", admin);
- }
- catch(Exception ex)
- {
- log.Error("UploadRewardsMembership" + string.Concat(DateTime.Now.ToString(CultureInfo.InvariantCulture), " ", ex.Message), ex);
- return base.DisplaySessionError();
- }
- }
In repository, you can define InsertFCReward(), which will accept a data table. By using entity frame work, you can push the data to the data base. This method will return, the number of records inserted into the DB.

The reason why I chose this way is if you want to use OLEDB, then you have to install that in your machine. If you want to publish it then in the remote system, OLEDB has to be installed as well.
Hameedullah SalikPosted Jan 5, 2021, 5:39 AM
The view has made, which is the method for this view ?
Sourav Kumar DasPosted Dec 19, 2019, 5:09 AM
Nice and useful article.
Rushi MehtaPosted Dec 19, 2019, 4:08 AM
Thanks for sharing. Nice technical stuff
Prabakaran MPosted Dec 18, 2019, 10:54 PM
Nice Blog Thanks for sharing
Ankur MistryPosted Dec 18, 2019, 7:54 PM
Helpful stuff thank you for sharing