Romeo
Romeo

Reputation: 1841

Exporting data into CSV MVC4

Good day to all.. I'm very new to ASP.net programming so pardon my sample code. I have a controller that has this action code. I wanted to put the data from Employee table into a CSV file. Im not good at linq query yet, so i dont know how to get it by row. im using MVC4.

    public FileContentResult DownloadCSV()
    {

        //This is my linq query
        var EmployeeQry = from data in db.Employees
                          select data;

        //I want to put my Employee data into a CSV. something like this..
        string csv = "EmployeeName,EmployeePostion,EmployeeDepartment";
        return File(new System.Text.UTF8Encoding().GetBytes(csv),"text/csv","Report.csv");

    }

Upvotes: 1

Views: 10599

Answers (3)

Darren McGrath
Darren McGrath

Reputation: 87

This worked a treat for me (Will need adapting to your specific needs)

Put this in a controller named DownloadController

public void ExportToCSV()
        {
            StringWriter sw = new StringWriter();

            sw.WriteLine("\"First Name\",\"Last Name\",\"Email\",\"Organisation\",\"Department\",\"Job Title\"");

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=registereduser.csv");
            Response.ContentType = "application/octet-stream";

            ApplicationDbContext db = new ApplicationDbContext();

            var users = db.Users.ToList();

            foreach (var user in users)
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\"",

                user.FirstName,
                user.LastName,
                user.Email,
                user.Organisation,
                user.Department,
                user.JobTitle
                ));
            }
            Response.Write(sw.ToString());
            Response.End();

        }

& call using

<a href="@Url.Action("ExportToCSV", "Download")">download the CSV of registered users</a>

Upvotes: 5

Romeo
Romeo

Reputation: 1841

Thanks Matis.. but string.format is not working in linq. So I did the querying in the database and formatting locally.

public FileContentResult DownloadCSV()
{
    string csv = string.Concat(from employee in db.Employees
                               select employee.EmployeeCode + "," 
                               + employee.EmployeeName + "," 
                               + employee.Department + "," 
                               + employee.Supervisor + "\n");
    return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report.csv");
}

Upvotes: 1

Matis
Matis

Reputation: 513

Try this:

string csv = string.Concat(
             EmployeeQry.Select(
                    employee => string.Format("{0},{1},{2}\n", employee.Name, employee.Position, employee.Department)));

or this (the same with alternative syntax):

string csv = string.Concat(from employee in EmployeeQry
                              select string.Format("{0},{1},{2}\n", employee.Name, employee.Position, employee.Department));

Upvotes: 1

Related Questions