如何使用StringBuilder将数据从Structure输出到CSV

时间:2014-01-29 18:07:30

标签: vb.net stringbuilder records

我有以下结构的数据:

Structure student
    Dim stdntpass As String
    Dim fname As String
    Dim sname As String
    Dim age As Byte
    Dim year As Integer
    Dim stdntuser As String
End Structure

我需要获取该结构中的数据并将其输出到CSV。我打算使用StringBuilder对象来执行此操作,但我无法弄清楚如何将结构赋予StringBuilder

3 个答案:

答案 0 :(得分:0)

这是一个使用反射来确定student结构中存在哪些字段的函数:

Public Function StudentsToCSV(students As IEnumerable(Of student)) As String
    Const separator As Char = ";"c
    Dim sb As New StringBuilder

    'Get the data elements
    Dim studentFields = GetType(student).GetFields()

    'Output headline (may be removed)
    For Each field In studentFields
        sb.Append(field.Name)
        sb.Append(separator)
    Next
    sb.AppendLine("")

    'Write a line for each student
    For Each s In students
        'Write the value of each field
        For Each field In studentFields
            Dim value As String = Convert.ToString(field.GetValue(s))
            sb.Append(value)
            '... followed by the separator
            sb.Append(separator)
        Next
        sb.AppendLine("")
    Next
    Return sb.ToString()
End Function

您可以将students的任意一组传递给此函数 - 可能是数组,List(Of student)或其他任何内容。

答案 1 :(得分:0)

StringBuilder无法获取整个Structure并自动附加Structure中的每个属性。如果你必须使用StringBuilder,你可以这样做:

builder.Append(s.stdntpass)
builder.Append(",")
builder.Append(s.fname)
builder.Append(",")
builder.Append(s.sname)
builder.Append(",")
builder.Append(s.age)
builder.Append(",")
builder.Append(s.year)
builder.Append(",")
builder.Append(s.stdntuser)
Dim csvLine As String = builder.ToString()

但是,使用String.Join方法会更容易,例如:

Dim csvLine As String = String.Join(",", s.stdntpass, s.fname, s.sname, s.age, s.year, s.stdntuser)

您可以使用reflection从结构中动态获取属性列表,但是如果不使用属性或某些东西,您将无法控制字段的追加顺序难看。

在任何情况下,您都应该小心,正确转义值。如果结构中的任何字符串包含逗号,则需要用引号括起该字段。如果任何这些字符串引号,它们需要加倍。您可以使用以下方法修复值:

Public Function EscapeValueForCsv(value As String) As String
    Return """" & value.Replace("""", """""") & """"
End Function

然后,您可以在将每个属性传递给String.Join之前调用它:

Dim csvLine As String = String.Join _
    (
    ",", 
    EscapeValueForCsv(s.stdntpass), 
    EscapeValueForCsv(s.fname), 
    EscapeValueForCsv(s.sname), 
    EscapeValueForCsv(s.age.ToString()),
    EscapeValueForCsv(s.year.ToString()), 
    EscapeValueForCsv(s.stdntuser)
    )

答案 2 :(得分:0)

一种方法是覆盖ToString函数。现在将整个对象传递给stringbuilder或甚至将Tostring函数发送到文件将传递值你想要的值:

Structure student
    Dim stdntpass As String
    Dim fname As String
    Dim sname As String
    Dim age As Byte
    Dim year As Integer
    Dim stdntuser As String
    Public Overrides Function ToString() As String
        Return Join({stdntpass, fname, sname, age.ToString, year.ToString, stdntuser}, ","c) + vbNewLine
    End Function
End Structure