簡體   English   中英

將數據導出到CSV MVC4

[英]Exporting data into CSV MVC4

祝大家都好。.我對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");

    }

這對我來說是一種享受(需要適應您的特定需求)

將其放在名為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>

嘗試這個:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM