You are currently viewing How to export .csv file from controller in .NET Core MVC App / Web API C#?
ASP.NET Core

How to export .csv file from controller in .NET Core MVC App / Web API C#?

How to export .csv file from controller in .NET Core MVC App / Web API C#?

When you are working with .NET core based application you might have problem while exporting a .csv file or we can say any file as an output. You might have tables that contain the records and and user want to export that records from the table in the .csv file then this blog helps you to create the same thing using .NET Core based c# code.

This blog post also helps you if you are looking for How to Export CSV files from ASP.NET core? or How can I return a CSV file in ASP.Net Core? or How to create a web API that returns .csv file as output? or How to return .csv file from .NET Core controller?

Ask Question

Lets take one example of you have table that contain the list of employee and you want to export that data into a .csv file when user click on the export button.

How to export .csv file from controller in .NET Core MVC App / Web API C#?
Export to .csv file in .NET Core Web API / MVC App

To implement the logic for the above functionality we need to create Employee Model and EmployeeCSVResult class and inherit EmployeeCSVResult from the FileResult. Please check the below code.

Create Employee Model

namespace EmployeeCsvResultDemo.Models
{
    public class Employee
    {
        public string Name {get;set;}
        public int Salary{get;set;}
        public int Age {get;set;}
    }
}

Create EmployeeCSVResult Model

using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;


namespace EmployeeCsvResultDemo.Models
{
    public class EmployeeCsvResult : FileResult
    {
        private readonly IEnumerable<Employee> _employeeData;

        public EmployeeCsvResult(IEnumerable<Employee> employeeData, string fileDownloadName) : base("text/csv")
        {
            _employeeData= employeeData;
            FileDownloadName = fileDownloadName;
        }

        public async override Task ExecuteResultAsync(ActionContext context)
        {
            var response = context.HttpContext.Response;
            context.HttpContext.Response.Headers.Add("Content-Disposition", new[] { "attachment; filename=" + FileDownloadName });

            using (var streamWriter = new StreamWriter(response.Body)) {
              await streamWriter.WriteLineAsync(
                $"Name, Salary, Age"
              );
              foreach (var p in _employeeData)
              {
                await streamWriter.WriteLineAsync(
                  $"{p.Name}, {p.Salary}, {p.Age}"
                );
                await streamWriter.FlushAsync();
              }
              await streamWriter.FlushAsync();
            }
        }

    }
}

Now we can implement the below action method in the controller.

namespace EmployeeCsvResultDemo.Controllers
{
    public class EmployeeController : Controller
    {
//other action methods
		// GET: Export employee
        public async Task<IActionResult> ExportEmployeeData()
        {
			//code to get employee list
			var employeeData = _employeeService.GetEmployeeData();
			fileDownloadName ="employee.csv";
            return new EmployeeCsvResult(employeeData, fileDownloadName);
        }
	}
}
Change the export file type

If you want to export to some different type you can change the argument into the constructor base method of EmployeeCsvResult class and according to that, you can change the logic inside the EmployeeCsvResult class.