1

我正在将一个 excel 表导入我的 sql 数据库。一切正常,但我想将列标题作为静态值读取。不知道该怎么做。这是我用来阅读表格的代码:

    'Connection String to Excel Workbook   
    Dim excelConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & MyFile & ";Extended Properties=""Excel 12.0;HDR=Yes;"""

    ' Create Connection to Excel Workbook   
    Using connection As New System.Data.OleDb.OleDbConnection(excelConnectionString)

        'List columns you need from the Excel file   
        Dim command As New System.Data.OleDb.OleDbCommand("Select * FROM [" & txtSheetName.Text & "$]", connection)
        connection.Open()

        ' Create DbDataReader to Data Worksheet   
        Using dr As System.Data.OleDb.OleDbDataReader = command.ExecuteReader()

            Dim strSql As String = ""

            strSql = "INSERT INTO tblMine (" & _
                    "Header1, Field1, Field2 " & _
                     ") VALUES (" & _
                    "Header1, Field1, Field2)"

            Try
                If dr.HasRows() Then

                    While dr.Read()

                        If Convert.ToString(dr.Item(1)) <> "" Then

                            Dim cmd As New SqlClient.SqlCommand
                            cmd.Connection = cn
                            cmd.CommandType = CommandType.Text
                            cmd.CommandText = strSql
                            'DataTable1.Columns[0].ColumnName 
                            cmd.Parameters.Add("@Header1", SqlDbType.VarChar).Value = ???
                            cmd.Parameters.Add("@Field1", SqlDbType.VarChar).Value = Convert.ToString(dr.Item(0))
                            cmd.Parameters.Add("@Field2", SqlDbType.Int).Value = Convert.ToInt32(dr.Item(1))

                            cmd.ExecuteScalar()

                        End If

                    End While

                End If
4

1 回答 1

2

不是一个非常干净的代码,但这给出了 Header1 (或第一行中的名称,您的工作表的第一列名为 [" & txtSheetName.Text & "$]"

Dim cmd2 As OleDbCommand = New OleDbCommand("SELECT * FROM [" & txtSheetName.Text & "$] where 1=0", connection)
Dim da As OleDbDataAdapter = new OleDbDataAdapter(cmd2)
Dim dt As DataTable = new DataTable()
da.Fill(dt)
string header1 = dt.Columns(0).ColumnName

一点优化

     Dim cmd As New SqlClient.SqlCommand
     cmd.Connection = cn
     cmd.CommandType = CommandType.Text
     cmd.CommandText = strSql
     cmd.Parameters.AddWithValue("@Header1", header1) ' this is invariant
     cmd.Parameters.AddWithValue("@Field1", string.Empty) ' this is a dummy value
     cmd.Parameters.AddWithValue("@Field2", 0)  ' this is a dummy value
     While dr.Read()
         If Convert.ToString(dr.Item(1)) <> "" Then
              cmd.Parameters("@Field1").Value = Convert.ToString(dr.Item(0))
              cmd.Parameters("@Field2").Value = Convert.ToInt32(dr.Item(1))
              cmd.ExecuteScalar()
         End If
    End While
于 2012-06-15T14:50:50.190 回答