导出到csv - Linq查询

时间:2012-02-16 00:50:45

标签: c# linq linq-to-entities

我在linq中有一个查询db表的类,问题是: 如何将该数据导出到csv?我已经尝试了链接建议,我正在使用linq2csv,仍然想知道如何通过他们的订单获取列?谢谢!

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

3 个答案:

答案 0 :(得分:2)

为了控制排序顺序,您必须使用

等属性定义类
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; }
}

然后更改linq查询以使用此类,例如

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

答案 1 :(得分:1)

由于你已经熟悉LINQ,我之前使用过Matt Perdeck的LINQ2CSV(http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library),这让我的生活变得更加轻松。

答案 2 :(得分:1)

除非您在所有属性上使用[CsvColumn(FieldIndex = 1)]属性,否则LINQtoCSV不会保留您的列顺序。但是谁想这样做?我会使用ServiceStack.Text库。它默认保留列顺序。像这样工作:

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