从字符串转换为日期类型无效

问题描述 投票:0回答:1

我正在尝试从 Excel 文件 > 数据表 > 数据集 > Db 数据表导入数据

”因为我真的不明白问题实际上是从哪里开始所以这是一个相当长的代码“

(错误行:

Dim Date1 As DateTime = dtrow(1)

Dim dt1 As New DataTable Dim dt2 As New DataTable Dim firstrow As Boolean = True For Each row As IXLRow In ws2.Rows.Skip(1) If firstrow Then For Each cell As IXLCell In row.Cells dt1.Columns.Add(cell.Value.ToString) Next firstrow = False End If Exit For Next For Each row As IXLRow In ws2.Rows.Skip(2) dt1.Rows.Add() Dim i As Integer = 0 For Each cell As IXLCell In row.Cells() dt1.Rows(dt1.Rows.Count - 1)(i) = cell.Value.ToString() i += 1 Next Next 'importing data from dt1 into db' ds.Tables.Add(dt1) da.TableMappings.Add("Table", "dbo.fingerprintslogs") ds.Tables(0).TableName = "Table" conn.Open() Dim query = " Delete From Fingerprintlogs" Dim cmd As New SqlCommand(query, conn) da.DeleteCommand = cmd da.DeleteCommand.ExecuteNonQuery() DataGridView1.DataSource = ds.Tables(0) For Each dtrow As DataRow In ds.Tables(0).Rows Dim EmployeeID As Integer = dtrow(0) Dim Date1 As DateTime = dtrow(1) Dim WeekDay = dtrow(2) Dim Firstcheckin As DateTime = dtrow(3) Dim Lastcheckout As DateTime = dtrow(4) Dim query1 = "INSERT INTO fingerprintslogs Values('" & EmployeeID & "','" & Date1 & "','" & WeekDay & "','" & Firstcheckin & "','" & Lastcheckout & "')" Dim cmd1 As New SqlCommand(query1, conn) cmd1.Parameters.Add("@EmloyeeID", SqlDbType.Int).Value = EmployeeID cmd1.Parameters.Add("@Date1", SqlDbType.DateTime).Value = Date1 cmd1.Parameters.Add("@WeekDay", SqlDbType.NVarChar).Value = WeekDay cmd1.Parameters.Add("@Firstcheckin", SqlDbType.DateTime).Value = Firstcheckin cmd1.Parameters.Add("@Lastcheckout", SqlDbType.DateTime).Value = Lastcheckout cmd1.ExecuteNonQuery() da.InsertCommand = cmd1 da.Update(ds.Tables(0)) Next conn.Close()
此处发生错误“

从字符串“2024-04-15”转换为类型“日期”无效”:Dim Date1 As DateTime = dtrow(1)


这是最初来自 Excel 文件的数据示例:

先进后出员工ID日期平日首次入住最后退房102024-04-15星期一15:04102024-04-16星期二08:4614:41102024-04-17周三08:34
  • 我确保 Excel 文件上的所有列都设置为日期

  • 我尝试在此处填写数据表时删除.ToString:

    For Each cell As IXLCell In row.Cells() dt1.Rows(dt1.Rows.Count - 1)(i) = cell.Value.ToString() i += 1 Next
    
    
  • 我确保该列在数据库中设置为“日期”并且当“Date1”变量为“日期”时

  • 然后我尝试将所有内容更改为日期时间 错误仍然出现。

sql-server vb.net sqldatatypes
1个回答
0
投票
我不知道 VB 无法自动识别日期的问题根源,但这个示例应该对您有帮助。

Dim Date1 As Date = Date.ParseExact(dtrow(1).ToString(), "yyyy-MM-dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)
    
© www.soinside.com 2019 - 2024. All rights reserved.