CSV (Comma Separated Values) to DataTable

sampoo

Active member
Joined
Jun 12, 2004
Messages
25
Location
Belgium
Programming Experience
3-5
Hi,

I need to convert data which is stored in a string as raw data (Comma Separated Values) to a DataTable, which should then be added to a dataset.
Is this possible, and how (without having to write the data to a file)?


Thanks a lot
 
This function should help, just pass in your delimiter )"," for Comma Seperated) and the path of the CSV file:

VB.NET:
  Function delimitedDataSet(ByVal strDelimiter As String, ByVal strFilePath As String) As String
  		Dim oDS As New DataSet
  		Dim strFields As String
  		Dim oTable As New DataTable
  		Dim oRows As DataRow
  		Dim intCounter As Int32 = 0
  		Dim oRow As DataRow()
  		Dim cancel As Boolean
  
  		Dim oSR As New StreamReader(strFilePath)
  		
  		'Go to the top of the file
  		oSR.BaseStream.Seek(0, SeekOrigin.Begin)
  		
  		'Add in the Header Columns
  		For Each strFields In oSR.ReadLine().Split(strDelimiter.ToCharArray)
  			oDS.Tables(0).Columns.Add(strFields)
  		Next
  
  		'Now add in the Rows
  		oTable = oDS.Tables(0)
  		While (oSR.Peek() > -1)
  			oRows = oTable.NewRow()
 			For Each strFields In oSR.ReadLine().Split(strDelimiter.ToCharArray)
  				If intCounter = 0 Then
 				 If strFields <> "" Then
 					 oRows(intCounter) = strFields
 					 intCounter = intCounter + 1
  					Else
 					 cancel = True
 					 Exit For
  					End If
  				Else
 				 oRows(intCounter) = strFields
  				    intCounter = intCounter + 1
  				End If
  			Next
  			If cancel Then
  				intCounter = 0
  			Else
  				intCounter = 0
  				oTable.Rows.Add(oRows)
  			End If
  		End While
  
  		Return oDS.GetXml()
  	End Function
 
Back
Top