gpt4 book ai didi

c# - 导出到 csv - Linq 查询

转载 作者:太空狗 更新时间:2023-10-29 23:25:30 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于c# - 导出到 csv - Linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9303980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com