Smokey Grindel said:
Is it possible to export a single (not related to anything else) data
table's contents to a CSV file?
Here's some code you can adapt to your needs: (watch out for word-wrap)
Public Sub DataTableToCSV(ByVal path As String, ByVal table As DataTable,
Optional ByVal ignoreColumn As Integer = -1)
'Export a single DataTable's contents to a CSV file
'Having the ability to ignore the outputting on one column (like a record
id)
Dim output As StreamWriter
Dim delim As String = ""
' Write out the header row
Try
output = New StreamWriter(path, False)
For Each col As DataColumn In table.Columns
If col.Ordinal <> ignoreColumn - 1 Then
output.Write(delim)
output.Write(col.ColumnName)
delim = ","
End If
Next
output.WriteLine()
Catch ex As Exception
MessageBox.Show("The data could not be output to the selected file name."
& vbCrLf & vbCrLf & vbCrLf & ex.Message, AppDesc, MessageBoxButtons.OK,
MessageBoxIcon.Information)
Exit Sub
End Try
' write out each data row
For Each row As DataRow In table.Rows
nTotRows = nTotRows + 1
Dim iCol As Integer = 0
delim = ""
For Each value As Object In row.ItemArray
iCol = iCol + 1
If iCol <> ignoreColumn Then
output.Write(delim)
If TypeOf value Is String Then
output.Write(""""c) ' thats four double quotes and a c
output.Write(value)
output.Write(""""c) ' thats four double quotes and a c
Else
output.Write(value)
End If
delim = ","
End If
Next
Try
output.WriteLine()
Catch ex As Exception
MessageBox.Show("The data could not be output to the selected file
name." & vbCrLf & vbCrLf & vbCrLf & ex.Message, AppDesc,
MessageBoxButtons.OK, MessageBoxIcon.Information)
frm.Close()
frm.Dispose()
Exit Sub
End Try
Next
Try
output.Close()
frm.Close()
frm.Dispose()
Catch ex As Exception
MessageBox.Show("The data could not be output to the selected file name."
& vbCrLf & vbCrLf & vbCrLf & ex.Message, AppDesc, MessageBoxButtons.OK,
MessageBoxIcon.Information)
Exit Sub
End Try
End Sub