Hello Friends,
U can create CSV file using below code.
Call below GetRecord() function in your button click event or wherver u need.
Folder name and file name will be get from .config file.
Sub GetRecord()
Dim dt As DataTable
Dim Id As Integer
Id = Convert.ToInt32(ConfigurationSettings.AppSettings("Id").ToString())
Dim ds As DataSet = SqlHelper.ExecuteDataset(sConnString, "Get_Record", Id)
Dim headers(ds.Tables(0).Columns.Count) As String
Dim cnt As Integer = 0
For Each column As DataColumn In ds.Tables(0).Columns
headers(cnt) = column.ColumnName
cnt = cnt + 1
Next
ExportCSV(ds, 0, headers)
End Sub
Sub ExportCSV(ByRef ds As DataSet, ByVal tableIndex As Int32, ByRef headers As String())
'Write out column headers
Dim headerOut As String = ""
If Not headers Is Nothing Then
For i As Integer = 0 To headers.Length - 2 'Don't do the last item yet
headerOut += headers(i)
headerOut += ","
Next
headerOut += headers(headers.Length - 1) 'Now do the last item, so you don't have a trailing comma.
'CSVWriter.WriteLine(headerOut)
End If
headerOut += Environment.NewLine
'Write out data
Dim CSVOut As String = ""
For Each r As DataRow In ds.Tables(tableIndex).Rows
For i As Integer = 0 To (ds.Tables(tableIndex).Columns.Count - 2) 'Don't do the last item yet
If Not IsDBNull(r(i)) Then
CSVOut += Chr(34)
CSVOut += CStr(r(i))
CSVOut += Chr(34)
End If
CSVOut += ","
Next
If Not IsDBNull(r(ds.Tables(tableIndex).Columns.Count - 1)) Then
CSVOut += CStr(r(ds.Tables(tableIndex).Columns.Count - 1)) 'Now do the last item, so you don't have a trailing comma.
End If
CSVOut += Environment.NewLine
'CSVWriter.WriteLine(CSVOut)
Next
Dim sFileName As String = ConfigurationSettings.AppSettings("FileName").ToString()
Dim dtTime As DateTime
dtTime = DateTime.Now()
Dim swOut As New StreamWriter(sADPOut + "\" + sFileName & "_" & dtTime.ToString.Replace("/", "").Replace(":", "") + ".csv")
swOut.Write(headerOut.ToString())
swOut.Write(CSVOut.ToString())
swOut.Flush()
swOut.Close()
End Sub
.CSV file will be save in specified folder.
Thursday, June 16, 2011
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment