Thamsanqa Ngcongwane

Thamsanqa Ngcongwane

  • NA
  • 184
  • 23.5k

How to export list data to excel in C#

Nov 20 2019 3:59 AM
The following is my c# code Im only stuck on the foreach part where by I have to insert data from list to excel.
  1. public IActionResult ExportData() {  
  2.  List < Users > ApplicationList = _context.Users.ToList();  
  3.  string sWebRootFolder = _hostingEnvironment.WebRootPath;  
  4.  string sFileName = @ "Candidates.xlsx";  
  5.  string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);  
  6.  FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));  
  7.  var memory = new MemoryStream();  
  8.  using(var fs = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Create, FileAccess.Write)) {  
  9.   IWorkbook workbook;  
  10.   workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();  
  11.   ISheet excelSheet = workbook.CreateSheet("Candidates");  
  12.   IRow row = excelSheet.CreateRow(0);  
  13.   foreach(var data in ApplicationList) {}  
  14.   workbook.Write(fs);  
  15.  }  
  16.  using(var stream = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open)) {  
  17.   stream.CopyTo(memory);  
  18.  }  
  19.  memory.Position = 0;  
  20.  return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);  
  21. }  

Answers (3)