CSV 파일을 읽고 데이터 테이블을 작성하는 함수가 있습니다. 나는 그것이 내 자신이 아니라고 주장하지 않을 것이다. 나는 그것을 어디에서 얻었는지 기억하지 못한다.CSV 파일에서 DataTable 만들기? ASP.net VB
값에 ","쉼표가있는 일부 CSV를 처리해야만 내 기능이 작동합니다. 누구든지이 문제를 해결하기 위해이 문제를 해결할 수 있도록 도와 줄 수 있습니까?
고마워요 ..
샘플 CSV 파일
FirstName, LastName, Comment, "address, just city",
John, Smith, "you are very good, but ugly", London,
Britney, Spear, "I am a singer, and beautiful", New York,
내 기능은 귀하의 문제가
Public Function BuildDataTable() As DataTable
Dim myTable As DataTable = New DataTable("MyTable")
Dim i As Integer
Dim myRow As DataRow
Dim fieldValues As String()
Dim myReader As IO.StreamReader
Dim csv2xml As New csv2xml
Try
'Open file and read first line to determine how many fields there are.
myReader = File.OpenText(_fileFullPath)
fieldValues = myReader.ReadLine().Split(_seperator)
'Create data columns accordingly
If _hasheader = False Then
For i = 0 To fieldValues.Length() - 1
myTable.Columns.Add(New DataColumn("Column(" & i & ")"))
Next
Else
'if the file has header, take the first row as header for datatable
For i = 0 To fieldValues.Length() - 1
myTable.Columns.Add(New DataColumn(fieldValues(i).Replace(" ", "")))
Next
End If
'Adding the first line of data to data table
myRow = myTable.NewRow
'if the csv file has not got a column header. defined by radio button list on first page by user
'if csv file has header, then not need to read the first line
If _hasheader = False Then
For i = 0 To fieldValues.Length() - 1
myRow.Item(i) = fieldValues(i).ToString
Next
myTable.Rows.Add(myRow)
End If
'Now reading the rest of the data to data table
While myReader.Peek() <> -1
fieldValues = myReader.ReadLine().Split(_seperator)
myRow = myTable.NewRow
For i = 0 To fieldValues.Length() - 1
myRow.Item(i) = fieldValues(i).Trim.ToString
Next
'check if there are empty rows in csv, ignore empty rows
If Not csv2xml.AreAllColumnsEmpty(myRow) = True Then
myTable.Rows.Add(myRow)
End If
End While
Catch ex As Exception
'MsgBox("Error building datatable: " & ex.Message)
Dim oError As ErrorLog = New ErrorLog
oError.LogError(_strWebsiteName, _
loginID, _
ex.Source.ToString, _
ex.Message.ToString, _
, _
ex.StackTrace.ToString)
oError = Nothing
Return New DataTable("Empty")
'Server.Transfer(CustomErrorPage)
Finally
csv2xml = Nothing
myRow = Nothing
End Try
myReader.Close()
Return myTable
End Function
이 질문을보십시오. http://stackoverflow.com/questions/1050112/how-to-read-a-csv-file-into-a-net-datatable ? rq = 1 – Steve
실수로 파일의 행과 필드를 구문 분석하는 코드 부분을 생략 한 것처럼 보입니다. 그것은 당신의 질문에 가장 관련이있는 코드의 부분이라고 생각됩니다. –