.net mvc epplus导出excel控制器视图全步骤
时间: 2023-05-21 16:06:20 浏览: 277
第一步:在控制器中添加以下代码
```c#
using OfficeOpenXml;
using System.IO;
using System.Web.Mvc;
public class ExportExcelController : Controller
{
private readonly IEmployeeRepository _employeeRepository;
public ExportExcelController(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
public FileResult Export()
{
var empList = _employeeRepository.GetAllEmployees();
ExcelPackage excelPackage = new ExcelPackage();
var sheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
sheet.Cells[1, 1].Value = "Employee Id";
sheet.Cells[1, 2].Value = "Full Name";
sheet.Cells[1, 3].Value = "Gender";
int row = 2;
foreach (var emp in empList)
{
sheet.Cells[row, 1].Value = emp.EmployeeId;
sheet.Cells[row, 2].Value = emp.FullName;
sheet.Cells[row, 3].Value = emp.Gender;
row++;
}
MemoryStream stream = new MemoryStream();
excelPackage.SaveAs(stream);
string fileName = $"Employees-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
}
```
第二步:在视图中添加以下代码
```html
@using (Html.BeginForm("Export", "ExportExcel", FormMethod.Post))
{
<button type="submit" class="btn btn-success">Export Excel</button>
}
```
第三步:在路由配置文件中添加以下代码
```c#
routes.MapRoute(
name: "ExportExcel",
url: "ExportExcel/Export",
defaults: new { controller = "ExportExcel", action = "Export" }
);
```
这样,当用户点击按钮时,将会生成一个包含所有员工信息的 Excel 文件并下载到用户的计算机上。
阅读全文