简体   繁体   English

如何使用vb.net将excel文件导入sql server

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

I need help with importing Excel file into SQL Server by using VB.NET.我需要有关使用 VB.NET 将 Excel 文件导入 SQL Server 的帮助。 My coding runs fine but sometimes it occur an ex message that said convert date failed我的编码运行良好,但有时会出现一条前消息,说转换日期失败

在此处输入图片说明

Here the error.这里的错误。 When I import it for the first time it work fine but after changing the primary key in excel and other things it error at date当我第一次导入它时,它工作正常,但在更改 excel 中的主键和其他事情后,它在日期出错

在此处输入图片说明

This is the date in the Excel file.这是 Excel 文件中的日期。 First time it works but second time it doesn't work.第一次有效,但第二次无效。 I write the date in Excel just like SQL Server date format like 2021-12-14 which is YYYY-MM-DD.我在 Excel 中写日期就像 SQL Server 日期格式,如 2021-12-14,即 YYYY-MM-DD。 I kinda confused about this for a month now... if i have 10 rows in Excel, sometime it occur the error about convert the date but still import the data into SQL Server but some of them not imported in sql我现在对此有点困惑了一个月......如果我在 Excel 中有 10 行,有时会发生关于转换日期但仍将数据导入 SQL Server 但其中一些未导入 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

This is my coding for import the Excel file.这是我导入 Excel 文件的编码。 I think here the wrong part.我认为这里是错误的部分。

You could make the code somewhat more efficient and add error-checking.您可以使代码更高效并添加错误检查。

You can use just one instance of an SQL command and change the values of its parameters to submit new data.您可以仅使用 SQL 命令的一个实例并更改其参数值以提交新数据。

When getting the values for those parameters, you can use functions like DateTime.TryParse , which gives you an opportunity to handle a parsing error however you want - you might skip the row, or add to an error log, instead of trying to insert invalid data.获取这些参数的值时,您可以使用DateTime.TryParse函数,这使您有机会根据需要处理解析错误 - 您可以跳过该行,或添加到错误日志中,而不是尝试插入无效的数据。

You could start from this example:你可以从这个例子开始:

'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

It is a good idea to specify the culture which is to be used when trying to parse dates or numbers, eg 1/12/2020 could be the first of January or January 12th.指定在尝试解析日期或数字时要使用的区域性是一个好主意,例如 1/12/2020 可以是 1 月的第一天或 1 月 12 日。

You could make the code somewhat more efficient and add error-checking.您可以使代码更高效并添加错误检查。

You can use just one instance of an SQL command and change the values of its parameters to submit new data.您可以仅使用 SQL 命令的一个实例并更改其参数值以提交新数据。

When getting the values for those parameters, you can use functions like DateTime.TryParse, which gives you an opportunity to handle a parsing error however you want - you might skip the row, or add to an error log, instead of trying to insert invalid data.获取这些参数的值时,您可以使用 DateTime.TryParse 之类的函数,这使您有机会根据需要处理解析错误 - 您可以跳过该行或添加到错误日志中,而不是尝试插入无效的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM