【问题标题】:Create sql Table programatically using column names of excel sheet vb.net使用excel表vb.net的列名以编程方式创建sql表
【发布时间】:2016-04-10 22:04:31
【问题描述】:

我正在尝试将 excel 表导入为 sql 表(列名已在 excel 表中) 我正在执行以下步骤以最终创建表。

第 1 步:浏览 excel 文件并使用 excel 工作表列表填充组合框。

Private Sub btnspibrowse_Click(sender As System.Object, e As System.EventArgs) Handles btnspibrowse.Click
    If openfile.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
        Cursor = Cursors.WaitCursor

        'Populating the Combobox with the sheet names
        xlconnstring = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + openfile.FileName + "; Extended Properties='Excel 12.0 Xml;HDR=YES'")
        Dim shtname As String = ""
        xldatatable = New DataTable
        Try 'for XL oledb


            'get the nams of sheets
            xlconnstring.Open()
            'help regarding getoledbschematale
            'https://support.microsoft.com/en-in/kb/309488
            'The OLE DB .NET Data Provider uses the GetOleDbSchemaTable method of the OleDbConnection object to expose schema information. 
            'GetOleDbSchemaTable returns a DataTable that is populated with the schema information.

            'The first argument of GetOleDbSchemaTable is the schema parameter, 
            'an OleDbSchemaGuid argument that identifies which schema information to return (such as tables, columns, and primary keys). 
            'The second argument is an Object array of restrictions to filter the rows that are returned in the schema DataTable 
            '(for example, you may specify restrictions for table name, type, owner, and /or schema).

            xldatatable = xlconnstring.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)

            Dim int As Integer = 0
            For int = 0 To xldatatable.Rows.Count - 1
                If xldatatable.Rows(int)!TABLE_TYPE.ToString = "TABLE" Then
                    cbodbsheet.Items.Add(xldatatable.Rows(int)!TABLE_NAME.ToString())
                End If
            Next
            xldatatable = Nothing
            xlconnstring.Close()
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical, "Database Import Error")
        End Try
    End If
    Cursor = Cursors.Default

End Sub

第 2 步:我选择所需的工作表并在 datagridview 中向用户显示工作表的一瞥

Private Sub cbodbsheet_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cbodbsheet.SelectedIndexChanged
    Cursor = Cursors.WaitCursor
    xlconnstring = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + openfile.FileName + "; Extended Properties='Excel 12.0 Xml;HDR=YES'")
    Dim shtname As String = ""
    Try 'for XL oledb
        xlcommand = New OleDbCommand
        xldatatable = New DataTable

        'get the nams of sheets
        xlconnstring.Open()
        Try
            'help regarding getoledbschematale
            'https://support.microsoft.com/en-in/kb/309488
            'The OLE DB .NET Data Provider uses the GetOleDbSchemaTable method of the OleDbConnection object to expose schema information. 
            'GetOleDbSchemaTable returns a DataTable that is populated with the schema information.

            'The first argument of GetOleDbSchemaTable is the schema parameter, 
            'an OleDbSchemaGuid argument that identifies which schema information to return (such as tables, columns, and primary keys). 
            'The second argument is an Object array of restrictions to filter the rows that are returned in the schema DataTable 
            '(for example, you may specify restrictions for table name, type, owner, and /or schema).

            xldatatable = xlconnstring.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)

            'Dim shtindex As Integer = xlschema.Rows.IndexOf(cbodbsheet.SelectedValue)
            shtname = xldatatable.Rows(cbodbsheet.SelectedIndex)("TABLE_NAME").ToString()
            xlconnstring.Close()
            xldatatable = Nothing
        Catch ex1 As Exception
            MsgBox(ex1, MsgBoxStyle.Critical, "Import Wizard-Excel Table Schema")
        End Try

        'read from selected sheet
        xlconnstring.Open()
        Try
            xldatatable = New DataTable
            xlcommand.CommandText = "SELECT * From [" & shtname & "]"
            xlcommand.Connection = xlconnstring
            xldataadapter.SelectCommand = xlcommand
            xldataadapter.Fill(xldatatable)
            xlconnstring.Close()
        Catch ex2 As Exception
            MsgBox(ex2.ToString(), MsgBoxStyle.Critical, "Import Wizard-Excel Command Query")
        End Try
        'bind data to gridview
        dgxlview.DataSource = xldatatable
    Catch ex3 As Exception
        MsgBox(ex3.ToString(), MsgBoxStyle.Critical, "Import Wizard-OLEDB Connection Problems")
    End Try
    spiselectedflag = True
    ' MsgBox(spiselectedflag)
    Cursor = Cursors.Default
    xldatatable = Nothing
    xlcommand = Nothing
    xldataadapter = Nothing
End Sub

第三步:选中的工作表有一个任意行数的表格(根据需要)。因此,单击按钮后,我需要首先创建一个包含此选定 Excel 表的所有列的表。 但我无法获取列。请用这个简单的东西指导我。

感谢阅读。

【问题讨论】:

  • 你为什么不只是创建一个数据表?如果创建数据表,则可以获取列名标题,然后创建一些存储过程以首先创建具有所需名称的表,然后插入行。存储过程看起来像这样 ALTER TABLE table_name ADD column_name 数据类型 - 列名将来自您的 excel 文件。
  • 感谢@codeMonger123 的回复。你能指导我从选定的excel表中提取列标题吗???我在使用 GetOleDbSchemaTable 提取列标题时遇到问题。休息我发现用存储过程来做。请用代码指导我。
  • 嗨,我现在正在从数据网格视图中提取列标题。并使用这些在 sql 中构建表。这是一个好习惯还是你认为我应该使用 oledbconnection 从 Excel 中读取列名???

标签: vb.net sql-server-2008


【解决方案1】:

我找到了使用数据表提取的方法。

代码直到this page 的第 5 步 和this page的答案

【讨论】:

    【解决方案2】:

    这是我最初花了一段时间才弄清楚的一些代码,但我现在一直将它用于 xlsx 和用于 csv 的类似代码。它很简单,并且根据我研究的最快的处理方法之一。它使用带有 xlsx 的任何内容的函数 GetFiles,将遍历该列表并基于该列表创建一个数据表。

    Friend Shared Function GetExcelFileToDataTable As DataTable
    
     Dim lstFilesToProcess() As String = Directory.GetFiles("YOURFILEPATH", "*.xlsx")
    
        Try
            Dim dt As New DataTable
            Dim Conn As System.Data.OleDb.OleDbConnection
            Dim cmd As System.Data.OleDb.OleDbDataAdapter
    
            If lstFilesToProcess.Length > 0 Then
                For Each ExcelFiles In lstFilesToProcess
    
                    Dim FileInfo As New FileInfo(ExcelFiles)
                    Dim strFileName As String = FileInfo.Name
    
                        Conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFiles + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1';")
                        Conn.Open()
                        Dim dtSheets As DataTable = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
                        Dim listSheet As New List(Of String)
                        Dim drSheet As DataRow
                        For Each drSheet In dtSheets.Rows
                            listSheet.Add(drSheet("TABLE_NAME").ToString())
                            cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [" & drSheet("TABLE_NAME").ToString() & "]", Conn)
                            cmd.TableMappings.Add("Table", "Net-informations.com")
                            cmd.Fill(dt)
                            Conn.Close()
                        Next
    
                Next
            End If
    
            Return dt
    
        Catch ex As Exception  
            Return Nothing
        End Try
    
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 2010-12-10
      • 2013-11-04
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      相关资源
      最近更新 更多