Export to csv - Linq query

烈酒焚心 提交于 2019-12-19 21:55:37

问题


I have a class in linq that query db table like this, and the question is: How do I export that data to csv? I have tried link suggested and I am using linq2csv and still want to know how to get column by their order? thanks!

var usr = from usr in db.User 
select new { usr.UserName, usr.Dept, usr.Name)
MainListView.DataSource = usr; 
MainListView.DataBind();

CsvFileDescription outputFileDescription = new CsvFileDescription
                {
                    SeparatorChar = ',',
                    FirstLineHasColumnNames = true,
                    FileCultureName = "en-US"
                };

                CsvContext cc = new CsvContext();
               string finalPath = mypath + "usr_" + DateTime.Now.ToString  ( "yyyyMMddhhmmssfff" ) + ".csv";
                cc.Write( usr, finalPath, outputFileDescription );

回答1:


In order to control the sort order you must define a class with attributes like

public class User
{
    [CsvColumn(FieldIndex = 1)]
    public string UserName { get; set; }

    [CsvColumn(FieldIndex = 2)]
    public string Dept { get; set; }

    [CsvColumn(FieldIndex = 3)]
    public string Name { get; set; }
}

Then you change your linq query to use this class, eg

string mypath = @".\";  

var usr = (from u in db.User select new User 
               { 
                   UserName = u.UserName, 
                   Dept     = u.Dept    ,  
                   Name     = u.Name 
               }
          );

CsvFileDescription outputFileDescription = new CsvFileDescription
    {
        SeparatorChar = ',',
        FirstLineHasColumnNames = true,
        FileCultureName = "en-US"
    };

CsvContext cc = new CsvContext();
string finalPath = mypath + "usr_" + DateTime.Now.ToString("yyyyMMddhhmmssfff" ) + ".csv";
cc.Write( usr, finalPath, outputFileDescription );



回答2:


Since you're already familiar with LINQ, I've used Matt Perdeck's LINQ2CSV ( http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library ) before and it's made my life a lot easier.




回答3:


LINQtoCSV doesn't preserve your column order unless you use the [CsvColumn(FieldIndex = 1)] attribute on all your properties. But who wants to do that? I would use ServiceStack.Text library. It preserves column orders by default. Works like this:

string csv = ServiceStack.Text.CsvSerializer.SerializeToCsv<>(exportData);



来源:https://stackoverflow.com/questions/9303980/export-to-csv-linq-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!