Skip to content

Instantly share code, notes, and snippets.

@gambitier
Created April 25, 2023 17:26
Show Gist options
  • Select an option

  • Save gambitier/e120b3720a269f0b6caa6dfef840f363 to your computer and use it in GitHub Desktop.

Select an option

Save gambitier/e120b3720a269f0b6caa6dfef840f363 to your computer and use it in GitHub Desktop.
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);
}
}
}
@gambitier
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment