如何使用 vb.net 将 excel 文件导入 sql 服务器

how to import excel file into sql server using vb.net

我需要帮助使用 VB.NET 将 Excel 文件导入 SQL 服务器。我的代码运行正常,但有时会出现一条 ex 消息,表示转换日期失败

这里是错误。当我第一次导入它时它工作正常但是在更改 excel 中的主键和其他东西后它在 date

出错

这是 Excel 文件中的日期。第一次有效,但第二次无效。我将日期写在 Excel 中,就像 SQL 服务器日期格式一样,如 2021-12-14,即 YYYY-MM-DD。我有点困惑一个月了...如果我在 Excel 中有 10 行,有时它会发生关于转换日期的错误但仍然将数据导入 SQL 服务器但其中一些没有在 sql

中导入
Try
    OLEcon.Open()
    With OLEcmd
        .Connection = OLEcon
        .CommandText = "select * from [Sheet1$]"
    End With
    OLEda.SelectCommand = OLEcmd
    OLEda.Fill(OLEdt)

    For Each r As DataRow In OLEdt.Rows
        Dim intAge As Integer
        intAge = Convert.ToInt32(r(2).ToString)
        Dim dateLED As Date
        dateLED = Convert.ToDateTime(r(11).ToString)
        Dim dateDJ As Date
        dateDJ = Convert.ToDateTime(r(12).ToString)

        sql = "INSERT INTO MasterStaffListTry (EENo,Name,Age,AgeCategory,Gender,Ethnicity,Grade,Category,Department,Position,ReportingTo,LastEmploymentDate,DateJoin,LOCUM,Status) VALUES 
                ('" & r(0).ToString & "','" & r(1).ToString & "','" & intAge & "','" & r(3).ToString & "','" & r(4).ToString & "',
                 '" & r(5).ToString & "' ,'" & r(6).ToString & "','" & r(7).ToString & "','" & r(8).ToString & "','" & r(9).ToString & "',
                 '" & r(10).ToString & "','" & dateLED.ToShortDateString & "','" & dateDJ.ToShortDateString & "','" & r(13).ToString & "' ,'" & r(14).ToString & "')"
        resul = saveData(sql)
        If resul Then
            Timer1.Start()
        End If
    Next

这是我导入 Excel 文件的代码。我认为这里是错误的部分。

您可以使代码更高效并添加错误检查。

您可以只使用 SQL 命令的一个实例并更改其参数值以提交新数据。

在获取这些参数的值时,您可以使用 DateTime.TryParse 等函数,这使您有机会根据需要处理解析错误 - 您可以跳过该行,或添加到错误日志中,而不是尝试插入无效数据。

你可以从这个例子开始:

'TODO: add all the parameters and set their .SqlDbType and .Size values to match the database columns.
Dim eeNo = New SqlParameter With {.ParameterName = "@EENo", .SqlDbType = SqlDbType.NVarChar, .Size = 16}
Dim name = New SqlParameter With {.ParameterName = "@Name", .SqlDbType = SqlDbType.NVarChar, .Size = 60}
Dim age = New SqlParameter With {.ParameterName = "@Age", .SqlDbType = SqlDbType.Int}
Dim lastEmploymentDate = New SqlParameter With {.ParameterName = "@LastEmploymentDate", .SqlDbType = SqlDbType.DateTime2}

'TODO: Write the query in full.
Dim sql = "INSERT INTO MasterStaffListTry (EENo,Name,Age,LastEmploymentDate)
                  VALUES 
                    (@EENo, @Name, @Age, @LastEmploymentDate)"

Dim ci = New CultureInfo("en-US")

Using conn As New SqlConnection("yourConnectionStringGoesHere")
    Using sqlcmd As New SqlCommand(sql, conn)
        'TODO: Add all the parameters.
        sqlcmd.Parameters.Add(eeNo)
        sqlcmd.Parameters.Add(name)
        sqlcmd.Parameters.Add(age)
        sqlcmd.Parameters.Add(lastEmploymentDate)

        Dim led As DateTime ' This will store the lastEmploymentDate when it has been parsed.

        For Each r As DataRow In oleDt.Rows

            'TODO: Use TryParse for all applicable data.
            Dim ledOK = DateTime.TryParse(r(11).ToString(), ci, Nothing, led)

            'TODO: Check all the parsing worked, e.g. If ledOK AndAlso variable2OK AndAlso variable3OK Then
            If ledOK Then
                eeNo.Value = r(0).ToString()
                name.Value = r(1).ToString()
                age.Value = Convert.ToInt32(r(2))
                lastEmploymentDate.Value = led

                sqlcmd.ExecuteNonQuery()

            End If

        Next

    End Using
End Using

最好在尝试解析日期或数字时指定要使用的文化,例如1/12/2020 可能是一月一日或一月 12 日。

您可以使代码更高效并添加错误检查。

您可以只使用 SQL 命令的一个实例并更改其参数值以提交新数据。

获取这些参数的值时,您可以使用 DateTime.TryParse 等函数,这使您有机会根据需要处理解析错误 - 您可以跳过该行,或添加到错误日志中,而不是尝试插入无效数据。