.NET如何从匿名类型的枚举输出csv?

时间:2010-06-08 21:06:22

标签: c# .net csv anonymous-types filehelpers

使用FileHelpers,我用[DelimitedRecord(",")]修饰了一个类,并将输出该类型的对象的枚举为CSV。但是,它没有用,因为我的类继承自ActiveRecordLinqBase<T>,这导致了一些问题。

所以,我想知道我是否可以只选择一个匿名类型的枚举,并以某种方式让filehelpers从中生成csv。我不喜欢只为FileHelpers定义一个类来输出csv。

我愿意使用另一个csv库,但FileHelpers已被证实。

修改

@Foovanadil:这就是我想做的事情:

CreateCSV(MyCollection.Select(x=>new{
    x.Prop1,
    x.Prop2,
    x.Prop3
}));

给你:

Prop1,Prop2,Prop3
val1a,val2a,val3a
val1b,val2b,val3b
etc.....

2 个答案:

答案 0 :(得分:3)

LINQ To CSV对我很有用。

以下是我如何使用它的示例:

protected void Page_Load(object sender, EventArgs e)
{
    var courseId = int.Parse(Request["id"]);
    var course = Course.Queryable.Single(x => x.Id == courseId);
    Response.ContentType = "text/csv";
    Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}.csv\";", course.Code));

    var csvContext = new LINQtoCSV.CsvContext();
    var writer = new System.IO.StreamWriter(Response.OutputStream);
    csvContext.Write(course.Registrations.Select(x => new
    {
        x.StudentId,
        x.Name,
        x.EmailAddress,
        x.MoodleUsername,
        x.Age,
        x.Is65OrOlder,
        x.CertificationAndRank,
        x.Citizenship,
        x.DateOfBirth,
        x.DepartmentName,
        x.StationNumber,        
        x.EmploymentStatus,
        x.HighestEducationLevel
    }), writer);        

    writer.Dispose();
}

更新

上述方法存在一些缺点:

  • csv文件中的列顺序是不可预测的。它不遵循匿名类型中属性定义的顺序。
  • 列标题来自属性名称,这些属性并不总是所需的。

所以,我决定只为CSV记录创建一个类,它最终没有比匿名类型更多的工作了。我使用Auto Mapper展平了我的源类并填充了CSV类的属性值。我还决定将FileHelpersLinq To CSV进行比较。在我的情况下,Linq To CSV显然是赢家:

  • L2CSV允许您将属性应用于类中的每个属性,以定义列顺序,列标题标题和转换格式。
  • FH只允许您为每个字段提供转换格式。列顺序取决于属性在类中定义的顺序。
  • FHs不会从属性名称推断列标题,也不允许您提供列标题。你可以提供一个文字字符串作为CSV文件的标题,这是不好的:分隔符内置在文字字符串中;列标题的顺序不与属性的顺序同步。

我希望这些发现很有用。这是我的新代码:

// CSV Class

public class CsvRegistration
{
    [CsvColumn(FieldIndex = 0)]
    public string Name { get; set; }

    [CsvColumn(FieldIndex = 1, Name = "Student Id")]
    public int StudentId { get; set; }

    [CsvColumn(FieldIndex = 2, Name = "Email Address")]
    public string EmailAddress { get; set; }

    [CsvColumn(FieldIndex = 3, Name = "Moodle Username")]
    public string MoodleUsername { get; set; }

    [CsvColumn(FieldIndex = 4, Name = "Dept. Name")]
    public string DepartmentName { get; set; }

    [CsvColumn(FieldIndex = 5, Name = "Station #")]
    public string StationNumber { get; set; }

    [CsvColumn(FieldIndex = 6, Name = "Highest Education Level")]
    public string HighestEducationLevel { get; set; }

    [CsvColumn(FieldIndex = 7, Name = "Certification/Rank")]
    public string CertificationAndRank { get; set; }

    [CsvColumn(FieldIndex = 8, Name = "Employment Status")]
    public string EmploymentStatus { get; set; }

    [CsvColumn(FieldIndex = 9, Name = "Registration Date")]
    public DateTime RegistrationDate { get; set; }

    [CsvColumn(FieldIndex = 10, Name = "Date of Birth")]
    public DateTime DateOfBirth { get; set; }

    [CsvColumn(FieldIndex = 11)]
    public int Age { get; set; }

    [CsvColumn(FieldIndex = 12)]
    public string Citizenship { get; set; }

    [CsvColumn(FieldIndex = 13)]
    public string Race { get; set; }

    [CsvColumn(FieldIndex = 14)]
    public string Ethnicity { get; set; }

    [CsvColumn(FieldIndex = 15, Name = "Home Address")]
    public string HomeAddressLine1 { get; set; }

    [CsvColumn(FieldIndex = 16, Name = "City")]
    public string HomeAddressCity { get; set; }

    [CsvColumn(FieldIndex = 17, Name = "State")]
    public string HomeAddressState { get; set; }

    [CsvColumn(FieldIndex = 18, Name = "Zip")]
    public string HomeAddressZip { get; set; }

    [CsvColumn(FieldIndex = 19, Name = "County")]
    public string HomeAddressCounty { get; set; }

    [CsvColumn(FieldIndex = 20, Name = "Home Phone")]
    public string HomePhone { get; set; }

    [CsvColumn(FieldIndex = 21, Name = "Work Phone")]
    public string WorkPhone { get; set; }
}


// ASPX page to serve csv file

protected void Page_Load(object sender, EventArgs e)
{
    var courseId = int.Parse(Request["id"]);
    var course = Course.Queryable.Single(x => x.Id == courseId);
    Response.ContentType = "text/csv";
    Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}.csv\";", course.Code));

    using (var writer = new System.IO.StreamWriter(Response.OutputStream))
    {
        var registrations = Mapper.Map<IEnumerable<Registration>, IEnumerable<CsvRegistration>>(course.Registrations);
        var cc = new LINQtoCSV.CsvContext();
        cc.Write(registrations, writer);
    }
}

答案 1 :(得分:2)

您的CreateCSV列表如下所示:

static StringBuilder CreateCSV<T>( IEnumerable<T> data )
{
    StringBuilder builder = new StringBuilder();
    var properties = typeof( T ).GetProperties();

    foreach ( var prop in properties )
    {   
        builder.Append( prop.Name ).Append( ", " );
    }

    builder.Remove( builder.Length - 2, 2 ).AppendLine();

    foreach ( var row in data )
    {
        foreach ( var prop in properties )
        {
            builder.Append( prop.GetValue( row, null ) ).Append( ", " );
        }

        builder.Remove( builder.Length - 2, 2 ).AppendLine();
    }

    return builder;
}