导入Excel工作表时读取列

时间:2012-06-15 14:17:23

标签: vb.net excel

我正在将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

1 个答案:

答案 0 :(得分: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