.net mvc epplus模拟真实数据导出execl
时间: 2023-05-21 17:03:35 浏览: 130
您可以使用 EPPlus 库来在 .NET MVC 中模拟真实数据并将其导出到 Excel。以下是一个简单的示例代码:
```csharp
using OfficeOpenXml;
using System.IO;
public ActionResult ExportToExcel()
{
// 模拟数据
var data = new List<MyModel>
{
new MyModel { Id = 1, Name = "John", Age = 30 },
new MyModel { Id = 2, Name = "Jane", Age = 25 },
new MyModel { Id = 3, Name = "Bob", Age = 40 }
};
// 创建 Excel 文件
var stream = new MemoryStream();
using (var package = new ExcelPackage(stream))
{
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
// 添加表头
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[1, 3].Value = "Age";
// 添加数据
var row = 2;
foreach (var item in data)
{
worksheet.Cells[row, 1].Value = item.Id;
worksheet.Cells[row, 2].Value = item.Name;
worksheet.Cells[row, 3].Value = item.Age;
row++;
}
// 自适应列宽
worksheet.Cells.AutoFitColumns();
}
// 返回 Excel 文件
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "data.xlsx");
}
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
```
这段代码将模拟数据导出到名为 "data.xlsx" 的 Excel 文件中,并将其作为文件下载返回给用户。您可以根据需要修改代码以适应您的情况。
阅读全文