CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

Column Name not displaying Using Mapping

Open amitpunekar opened this issue 1 year ago • 1 comments

Public Sub ExecuteSQL()
        Dim records As New List(Of Foo)
        Using cn As ReliableSqlConnection = connection_string
            Using cm As SqlCommand = cn.CreateCommand()
                cn.Open()
                With cm
                    .CommandType = CommandType.Text
                    .CommandText = sql
                    Using dr As New SafeDataReader(cm.ExecuteReader)
                        While dr.Read
                            Dim foo As Foo = New Foo()
                            foo.Id = 1
                            foo.Name = "Amit"
                            records.Add(foo)
                        End While
                    End Using
                End With
            End Using

            Using writer As New StreamWriter("C:\\LocalDev\\file.csv")
                Using csv As New CsvWriter(writer, CultureInfo.InvariantCulture)
                    csv.WriteHeader(Of Foo)()
                    csv.NextRecord()
                    For Each record As Foo In records
                        csv.WriteRecord(record)
                        csv.NextRecord()
                    Next
                End Using
            End Using
        End Using
    End Sub


    Public Class Foo

        Public Property Id As Integer
        Public Property Name As String
    End Class

    Public Class FooMap
        Inherits ClassMap(Of Foo)

        Public Sub New()
            Map(Function(m) m.Id).Name("Column One")
            Map(Function(m) m.Name).Name("Column Two")
        End Sub
    End Class

I have this above code in VB.net. I have two comuns "Id" and "Name" and I want the neames of this column to display as "Column One " and "Colum Two" respectively. i have implemented the logic to map the columns with the name. But the names of the columns in the header appear as "Id" and "Name" which are the name of the properties. Any suggestions if I am missing anytihng

image

amitpunekar avatar Feb 20 '24 17:02 amitpunekar

You need to register your class map.

csv.Context.RegisterClassMap<FooMap>();

JoshClose avatar Feb 29 '24 16:02 JoshClose