将数据导出到CSV MVC4 [英] Exporting data into CSV MVC4

查看:68
本文介绍了将数据导出到CSV MVC4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

祝大家有美好的一天..我对ASP.net编程非常陌生,所以请原谅我的示例代码.我有一个具有此操作代码的控制器.我想将Employee表中的数据放入CSV文件中.我还不擅长linq查询,所以我不知道如何按行获取它.我正在使用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");

    }

推荐答案

尝试一下:

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

这篇关于将数据导出到CSV MVC4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆