将数据导出为CSV MVC4

时间:2013-05-11 19:08:16

标签: 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");

    }

3 个答案:

答案 0 :(得分: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();

        }

&安培;使用

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

答案 1 :(得分:1)

试试这个:

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

或者这(与替代语法相同):

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

答案 2 :(得分:1)

感谢Matis ..但是string.format在linq中不起作用。所以我在数据库中进行查询并在本地进行格式化。

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");
}