C# 导出到CSV

''' <summary>
''' 数据导出
''' </summary>
''' <param name="dt"></param>
''' <param name="fileName"></param>
''' <remarks></remarks>
Public Sub SaveCSV(ByVal dt As DataTable, ByVal fileName As String)

Dim fs As New FileStream(fileName, FileMode.Create, FileAccess.Write)
Dim sw As New StreamWriter(fs, Encoding.Default)
Dim strs() As String

'title
Dim ar(dt.Columns.Count - 1) As DataColumn
dt.Columns.CopyTo(ar,
0)
strs
= Array.ConvertAll(ar, New Converter(Of DataColumn, String)(AddressOf DataColumnToString))
sw.WriteLine(
String.Join(",", strs))

'data
For i = 0 To dt.Rows.Count - 1
strs
= Array.ConvertAll(dt.Rows(i).ItemArray, New Converter(Of Object, String)(AddressOf ObjectToString))
sw.WriteLine(
String.Join(",", strs))
Next i

sw.Flush()
sw.Close()
fs.Dispose()
End Sub

Public Function ObjectToString(ByVal obj As Object) As String
Return obj.ToString()
End Function
Public Function DataColumnToString(ByVal dc As DataColumn) As String
Return dc.ColumnName
End Function
posted @ 2011-03-11 15:09  cnbwang  阅读(386)  评论(0编辑  收藏  举报