Fetach Data from Excel and store in a list using Dotnet
In this Session, We will know how to get data from an Excel sheet to our Dotnet code.
Firstly, We have to get sheet into the class for that we use AuthKey,IFormFile format as below:
[HttpPost] [Route("Bulkexcel")] public IActionResult execel_upload(IFormFile file) { //Code here }
then import the excel: as below:
string filename=Directory.GetCurrentDirectory()+"/Upload/ExcelFiles/"+file.FileName; using (FileStream fileStream = System.IO.File.Create(filename)) { file.CopyTo(fileStream); fileStream.Flush(); } [HttpPost] [Route("Auth/Bulkexcel")] public IActionResult execel_upload(IFormFile file) { try{ string filename=Directory.GetCurrentDirectory()+"/Upload/ExcelFiles/"+file.FileName; using (FileStream fileStream = System.IO.File.Create(filename)) { file.CopyTo(fileStream); fileStream.Flush(); } var List=this.get_list(file.FileName); for(int i=1;i<List.Count;i++){ //Insert Action or Any action on data we get from excel } //StatusCode = 200; }catch(Exception e){ //StatusCode = 416; } return Ok(res); } private List<Import> get_list(string fName) { List<Import> L_list= new List<Import>(); var filename=$"{Directory.GetCurrentDirectory()}{@"\Upload\ExcelFiles"}"+"\\"+fName; System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); using (var stream=System.IO.File.Open(filename,FileMode.Open,FileAccess.Read)) { using(var reader=ExcelReaderFactory.CreateReader(stream)) { while(reader.Read()) { L_list.Add(new Import() { phone_number=reader.GetValue(0).ToString(), address=reader.GetValue(1).ToString(), location=reader.GetValue(2).ToString(), }); } } } return L_list; //this function will return the data in the coloum number as we extract it from file... }
Thank you...