1

大家好.. 我对 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");

    }
4

3 回答 3

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>
于 2015-09-29T11:59:34.323 回答
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");
}
于 2013-05-12T10:24:07.243 回答
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));
于 2013-05-11T19:57:36.733 回答