Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export to csv - Linq query

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 );
like image 517
FAA Avatar asked Oct 09 '22 15:10

FAA


1 Answers

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 );
like image 53
sgmoore Avatar answered Oct 12 '22 10:10

sgmoore