.net mvc epplus用list添加几条数据导出excel全步骤
时间: 2023-05-22 16:06:20 浏览: 80
感谢您的提问。下面是使用 .net mvc epplus 将 list 中的几条数据导出到 excel 的全步骤:
1. 在 .net mvc 项目中添加 epplus nuget 包引用。
2. 新建一个 class,用于存储需要导出的数据。本例中,存储的是学生的信息。
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
3. 在需要导出数据的控制器中,创建一个 List<Student>,并添加数据。
public ActionResult ExportToExcel()
{
List<Student> students = new List<Student>();
students.Add(new Student { Name = "Tom", Age = 18, Gender = "Male" });
students.Add(new Student { Name = "Lucy", Age = 19, Gender = "Female" });
students.Add(new Student { Name = "Jack", Age = 20, Gender = "Male" });
4. 使用 epplus 库创建 excel 文件,并指定 excel 文件的名称和路径。
using (ExcelPackage excel = new ExcelPackage())
{
var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
workSheet.Cells[1, 1].Value = "Name";
workSheet.Cells[1, 2].Value = "Age";
workSheet.Cells[1, 3].Value = "Gender";
int row = 2;
foreach (var student in students)
{
workSheet.Cells[row, 1].Value = student.Name;
workSheet.Cells[row, 2].Value = student.Age;
workSheet.Cells[row, 3].Value = student.Gender;
row++;
}
string fileName = "StudentInfo.xlsx";
byte[] fileContents = excel.GetAsByteArray();
return File(fileContents, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
}
5. 在控制器的返回值中,将 excel 文件的内容作为一个文件流进行返回。
使用以上代码,可以将 list 中的数据导出到 excel 文件中,格式如下所示:
| Name | Age | Gender |
|------|-----|--------|
| Tom | 18 | Male |
| Lucy | 19 | Female |
| Jack | 20 | Male |
希望我的回答能够帮到您。