uploading and reading from an excel file in asp.net core 2

前端 未结 5 1302
野趣味
野趣味 2020-12-20 08:35

previously Asp.Net MVC had this third party library which easily allowed uploading and reading from an excel file called Excel Data Reader. We didn\'t need to have the file

5条回答
  •  被撕碎了的回忆
    2020-12-20 09:11

    I Could Read Excel File In 'Asp .Net Core' By This Code.

    Import And Export Data Using EPPlus.Core.

        [HttpPost]
        public IActionResult ReadExcelFileAsync(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return Content("File Not Selected");
    
            string fileExtension = Path.GetExtension(file.FileName);
            if (fileExtension != ".xls" && fileExtension != ".xlsx")
                return Content("File Not Selected");
    
            var rootFolder = @"D:\Files";
            var fileName = file.FileName;
            var filePath = Path.Combine(rootFolder, fileName);
            var fileLocation = new FileInfo(filePath);
    
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
    
             if (file.Length <= 0)
                 return BadRequest(GlobalValidationMessage.FileNotFound);  
    
             using (ExcelPackage package = new ExcelPackage(fileLocation))
             {
              ExcelWorksheet workSheet = package.Workbook.Worksheets["Table1"];
              //var workSheet = package.Workbook.Worksheets.First();
              int totalRows = workSheet.Dimension.Rows;
    
              var DataList = new List();
    
              for (int i = 2; i <= totalRows; i++)
               {
                      DataList.Add(new Customers
                        {
                       CustomerName = workSheet.Cells[i, 1].Value.ToString(),
                       CustomerEmail = workSheet.Cells[i, 2].Value.ToString(),
                       CustomerCountry = workSheet.Cells[i, 3].Value.ToString()
                       });
               }
    
                    _db.Customers.AddRange(customerList);
                    _db.SaveChanges();
                }
            return Ok();
    }
    

提交回复
热议问题