4

使用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.....
4

2 回答 2

4

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);
    }
}
于 2010-06-09T13:30:11.113 回答
3

您的 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;
}
于 2010-06-09T13:17:31.293 回答