Created
April 25, 2023 17:26
-
-
Save Gambitier/e120b3720a269f0b6caa6dfef840f363 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using ClosedXML.Excel; | |
public async Task<FileResult> ExportPeopleInExcel() | |
{ | |
var people = await context.People.ToListAsync(); | |
var fileName = "people.xlsx"; | |
return GenerateExcel(fileName, people); | |
} | |
private FileResult GenerateExcel(string fileName, IEnumerable<Person> people) | |
{ | |
DataTable dataTable = new DataTable("People"); | |
dataTable.Columns.AddRange(new DataColumn[] | |
{ | |
new DataColumn("Id"), | |
new DataColumn("Name") | |
}); | |
foreach (var person in people) | |
{ | |
dataTable.Rows.Add(person.Id, person.Name); | |
} | |
using (XLWorkbook wb = new XLWorkbook()) | |
{ | |
wb.Worksheets.Add(dataTable); | |
using (MemoryStream stream = new MemoryStream()) | |
{ | |
wb.SaveAs(stream); | |
return File(stream.ToArray(), | |
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", | |
fileName); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
reference: https://github.com/gavilanch/ExportExcelDemoMVC/blob/master/ExportExcelDemo/Controllers/HomeController.cs