将数据导出为CSV MVC4

Rom*_*meo 1 c# asp.net-mvc-4

祝大家好日子.我是ASP.net编程的新手,所以请原谅我的示例代码.我有一个具有此操作代码的控制器.我想将Employee表中的数据放入CSV文件中.我还不擅长linq查询,所以我不知道如何逐行获取它.即时通讯使用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");

    }
Run Code Online (Sandbox Code Playgroud)

小智 5

这对我有用(需要适应您的特定需求)

把它放在名为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();

        }
Run Code Online (Sandbox Code Playgroud)

并致电使用

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