导出到csv-Linq查询

本文关键字:查询 csv-Linq | 更新日期: 2023-09-27 18:24:51

我在linq中有一个类像这样查询数据库表,问题是:如何将数据导出到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 );

导出到csv-Linq查询

为了控制排序顺序,您必须定义一个具有等属性的类

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

由于您已经熟悉LINQ,我使用了Matt Perdeck的LINQ2CSV(http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library),这让我的生活轻松多了。

LINQtoCSV不会保留列顺序,除非在所有属性上使用[CsvColumn(FieldIndex=1)]属性。但谁愿意这么做呢?我会使用ServiceStack.文本库。默认情况下,它保留列顺序。工作原理如下:

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