【问题标题】:Insert null values into database through Excel通过 Excel 将空值插入数据库
【发布时间】:2020-03-23 10:58:07
【问题描述】:

我想通过导入 Excel 数据将值插入 SQL Server 数据库。代码插入 int、string 和 boolean 值。

当数据类型为 int 或 string 时,如何通过 Excel 工作表插入空值?

任何帮助将不胜感激。这是我的代码的一部分:

private final GetEmployeeFromExcelRow(DataRow row)
{
    return new final
        {
            EmpId = int.Parse(row[0].ToString()),
            Name = row[1].ToString(),
            Dept_Id = int.Parse(row[2].ToString()),
            isSupervisor = Boolean.Parse(row[3].ToString())
        };
}

【问题讨论】:

  • 能否请您提供 Excel 文件中的示例行并显示使用此方法创建的最终类?

标签: sql-server excel asp.net-mvc


【解决方案1】:

如果你愿意使用 VBA,试试这个。

Sub InsertInto()

'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String

'Create a new Connection object
Set cnn = New adodb.Connection

'Set the connection string
cnn.ConnectionString = "Your_Server_Name;Database=Your_DB_Name;Trusted_Connection=True;"

'Create a new Command object
Set cmd = New adodb.Command

'Open the connection
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn

'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText

'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = 2013-01-13 WHERE EMPID = 1"


'Pass the SQL to the Command object
cmd.CommandText = strSQL

'Open the Connection to the database
cnn.Open

'Execute the bit of SQL to update the database
cmd.Execute

'Close the connection again
cnn.Close

'Remove the objects
Set cmd = Nothing
Set cnn = Nothing

End Sub

同样,你也可以这样做。

Sub WriteDataToSQLServer()

    Dim cn                    As Object
    Dim rs                    As Object
    Dim n                     As Long
    Dim strQuery              As String

    Set cn = CreateObject("ADODB.Connection")

    With cn
        .Provider = "sqloledb"
        .ConnectionString = "Data Source=server_name;Initial Catalog=database_name;Integrated Security=SSPI;"
        .Open
    End With

    strQuery = "Table name here"

    Set rs = CreateObject("ADODB.Recordset")

    With rs
        .Open strQuery, cn, 1
        For n = 1 To 10
            .AddNew
            .Fields("Field1").Value = Cells(n, "A").Value
            .Fields("Field2").Value = Cells(n, "B").Value

            .Update
        Next n
        .Close
    End With

    cn.Close
    Set rs = Nothing
    Set cn = Nothing
End Sub

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 2013-12-13
    • 2019-04-29
    • 2019-04-29
    • 2017-06-21
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 2014-01-13
    相关资源
    最近更新 更多