Hi I'm trying to make export and return excell function with ClosedXml package. It works fine on demo project. I gotta make it for original project so this is the code.It's a IActionResult
public class HomeController : Controller
{
private List<Employee> employees = new List<Employee>
{
new Employee{ Id=1,Name="Jr.Dev",Role="Dev"},
new Employee{ Id=2,Name="Jr.Dev2",Role="Dev2"},
new Employee{ Id=3,Name="Jr.Dev3",Role="Dev3"},
new Employee{ Id=4,Name="Jr.Dev4",Role="Dev4"},
new Employee{ Id=5,Name="Jr.Dev5",Role="Dev5"},
};
public IActionResult Index()
{
return Excel();
}
public IActionResult Excel()
{
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("Employees");
var currentRow = 1;
worksheet.Cell(currentRow, 1).Value = "Id";
worksheet.Cell(currentRow, 2).Value = "Name";
worksheet.Cell(currentRow, 3).Value = "Role";
foreach (var item in employees)
{
currentRow++;
worksheet.Cell(currentRow, 1).Value = item.Id;
worksheet.Cell(currentRow, 2).Value = item.Name;
worksheet.Cell(currentRow, 3).Value = item.Role;
}
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Employee.xlsx");
}
}
}
}
It really works fine and downloads the xlsx file.
I just want to make a call from view like export excell and call it with viewmodel. How can I implement it with best practices.Thank you