2016-04-08 16 views
0

Bir excel sayfasını bir sql tablo olarak (excel sayfasında zaten sütun adları ile) ithal etmeye çalışıyorum Sonunda tablo oluşturmak için aşağıdaki adımları yapıyorum.sql tablo excel sayfa sütun adları kullanarak programlı olarak oluşturun sql

1. adım: excel dosyasına gözatın ve açılan kutuyu excel sayfalarının listesiyle doldurun.

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 

Aşama 2: gerekli tabaka seçip

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 

Adım 3 DataGridView kullanıcıya tabakanın bir belirti göstermektedir: bu göre (seçilen tabaka herhangi bir satır sayısının bir tablo vardır gereksinim). Bu nedenle, bir düğmeyi tıkladığınızda, öncelikle bu seçilen excel sayfasının tüm sütunlarını içeren bir tablo oluşturmanız gerekir. Ancak sütunları getiremiyorum. Lütfen bana bu basit şeyle yol göster.

Okumak için teşekkürler.

+0

Neden sadece bir veri tablosu oluşturmuyorsunuz? Veritabanını oluşturursanız, sütun adı üstbilgilerini alabilir ve daha sonra istenen adları içeren tabloyu oluşturmak için yumruklamak üzere bazı saklı yordamlar oluşturabilir ve ardından satırları ekleyebilirsiniz. Saklanan Proc bu ALTER TABLE tablo_adı ADD sütun_adı datatype gibi görünecektir - sütun adı excel dosyanızdan olacaktır. Yanıtlamak için – codeMonger123

+0

Thankyou @ codeMonger123. Seçilen excel sayfasından sütun başlıkları çıkarmak için bana rehberlik edebilir misiniz ??? GetOleDbSchemaTable kullanarak sütun başlıkları ayıklamak için sorun yaşıyorum. Geri kalanını saklı yordamla yapmayı buldum. Lütfen bana kodla yol göster. –

+0

Merhaba, şimdi datat ızgara görünümünden sütun başlıkları ayıklanıyor. ve bunları sql'de tablo oluşturmak için kullanın. İyi bir uygulama mı yoksa Excel'in sütun isimlerini oledbconnection kullanarak okumalı mıyım? –

cevap

0

ait Yanıt kadar

Kod İşte başlangıçta anlamaya biraz zaman aldı bazı kod, ama csv için xlsx ve benzeri kodu için şimdi hep kullanırım. Onun basit ve işlemek için en hızlı yollardan birini araştırdım. Bir işlev GetFiles'i xlsx'e sahip olan herhangi bir şeyle kullanır, bu listeden geçecek ve o listeye dayalı bir veri tabanı oluşturacaktır.

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