同时生成csv所有值都在第一列中

时间:2017-07-13 04:46:14

标签: vb.net winforms csv

我正在从数据阅读器创建csv文件。我的代码是这样的:

 While (dr.Read())

            sw = New StreamWriter(hht_Storage & "\Export\" & strfilename & ".csv", True)
            prcount = 0
            fvalues = ""
            For I = 0 To dr.FieldCount - 1
                If fvalues = "" Then
                    fvalues = IIf(IsDBNull(dr(I)), "", dr(I))
                    fvalues = Trim(Replace(fvalues, "'", ""))
                Else
                    fvalues = fvalues & vbTab
                    fvalues = fvalues & IIf(IsDBNull(dr(I)), "", dr(I))
                    fvalues = Trim(Replace(fvalues, "'", ""))
                End If
            Next I

            sw.WriteLine(fvalues)
            prcount = prcount + 1
            sw.Close()
        End While

但是我的CSV.i第一列中的所有值都要显示csv每列中的每个值。
任何帮助都非常明显。

2 个答案:

答案 0 :(得分:0)

数据读取器类实现IEnumerable接口,这意味着您可以调用Cast扩展方法来获取IEnumerable(Of Object),这是String.Join的类型方法接受:

Using writer As New StreamWriter("file path here")
    While myDataReader.Read()
        writer.WriteLine(String.Join(ControlChars.Tab, myDataReader.Cast(Of Object)()))
    End While
End Using

如果您需要处理每个项目,则只需添加Select电话:

Using writer As New StreamWriter("file path here")
    While myDataReader.Read()
        writer.WriteLine(String.Join(ControlChars.Tab,
                                     myDataReader.Cast(Of Object)().
                                                  Select(Function(o) o.ToString().
                                                                       Trim().
                                                                       Replace("'",
                                                                               String.Empty))))
    End While
End Using

现在正在将IEnumerable(Of String)传递给String.Join,但另一个重载只会在每个项目上调用ToString

答案 1 :(得分:0)

这应该有效(如果你愿意,可以将限制器更改为vbTab):

    Dim sb As New Text.StringBuilder
    sw = New StreamWriter(hht_Storage & "\Export\" & strfilename & ".csv", True)
    prcount = 0
    While (dr.Read())
        sb.Clear()
        For I As Integer = 0 To dr.FieldCount - 1
            If IsDBNull(dr(I)) = False Then sb.Append(dr(I).ToString)
            sb.Append(";") 'Field limiter
        Next I
        sw.WriteLine(sb.ToString)
        prcount = prcount + 1
    End While
    sw.Close()