我有以下代码从CSV文件导入数据。但是,日期列中的某些值为空,vb.net会出错。我该如何防止这种情况?
Dim datatabel As New DataTable()
datatabel.Columns.Add(New DataColumn("PLAASNO", GetType(String)))
datatabel.Columns.Add(New DataColumn("PLAASNAAM", GetType(String)))
datatabel.Columns.Add(New DataColumn("BLOKNO", GetType(String)))
datatabel.Columns.Add(New DataColumn("AREA", GetType(String)))
datatabel.Columns.Add(New DataColumn("DATUM", GetType(String)))
datatabel.Columns.Add(New DataColumn("NAME3", GetType(String)))
datatabel.Columns.Add(New DataColumn("KULTIVAR", GetType(String)))
datatabel.Columns.Add(New DataColumn("WINGKLAS", GetType(String)))
datatabel.Columns.Add(New DataColumn("ANALISEDATUM", GetType(Date)))
datatabel.Columns.Add(New DataColumn("SUIKER", GetType(Decimal)))
datatabel.Columns.Add(New DataColumn("pH", GetType(Decimal)))
datatabel.Columns.Add(New DataColumn("SUUR", GetType(Decimal)))
Dim parser As New FileIO.TextFieldParser("C:\Users\Administrator\Desktop\SKEDULERING\Data\LABANAL2.csv")
parser.Delimiters = New String() {","}
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
parser.ReadLine()
Do Until parser.EndOfData = True
Dim data As String() = parser.ReadFields()
For i As Integer = 0 To data.Length - 1
If (String.IsNullOrEmpty(data(i))) Then
data(i) = DBNull.Value.ToString
End If
Next
datatabel.Rows.Add(data)
Loop
我怀疑我的问题在于:
If (String.IsNullOrEmpty(data(i))) Then
data(i) = DBNull.Value.ToString
End If
错误是:字符串未被识别为有效的DateTime.Couldn存储在ANALISEDATUM列中。预期类型是DateTime
谢谢。
答案 0 :(得分:1)
试试这个。 OLEDB连接将获取excel文件并将其放入数据表中。
Public Shared Function GetCSV as Datatable
Dim dt As New DataTable
Dim ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "YourFile" & ";Extended Properties=""Text;HDR=Yes;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & "YOURFILENAME", conn)
da.Fill(dt)
Return dt
End Function