Epplus在NuGet中安装
![](https://i-blog.csdnimg.cn/blog_migrate/65f8730b8aa7ab5909812fed0cb58e9d.jpeg)
var excel = new ExcelPackage();
var worksheet = excel.Workbook.Worksheets.Add("Sheet1");
var recordIndex = 1;
var data = new List<Person>
{
new Person {Name = "张三",Age = 20,Birthday = DateTime.Now},
new Person {Name = "李四",Age = 30,Birthday = DateTime.Now}
}
foreach (var item in data)
{
worksheet.Row(recordIndex);
if (recordIndex == 1)
{
//表头
worksheet.Cells[recordIndex, 1].Value = "姓名";
worksheet.Cells[recordIndex, 2].Value = "年龄";
worksheet.Cells[recordIndex, 3].Value = "生日";
}
recordIndex++;
worksheet.Cells[recordIndex, 1].Value = item.Name;
worksheet.Cells[recordIndex, 2].Value = item.Age;
worksheet.Cells[recordIndex, 3].Value = item.Birthday?.ToString("yyyy/MM/dd");
}
var fileName = Guid.NewGuid() + ".xlsx";
var filePath = @"C:/Files/";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
using (var fs = File.OpenWrite(filePath + fileName))
{
excel.SaveAs(fs);
}
很简单,搞定