Controllo ListBox & inserisci dati

di il
6 risposte

Controllo ListBox & inserisci dati

Ho inserito all'interno di un form un controllo ListBox che mi serve per visualizzare dei dati

presenti in un file EXCEL. Carico i dati mediante ADO con la seguente routine:

On Error Resume Next
  Dim a As Long
  Dim b As Long
  Dim sSQLQry As String
  Dim ReturnArray
  Dim Conn As New ADODB.Connection
  Dim mrs As New ADODB.Recordset
  Dim icount As Long
  Dim DBPath As String, sconnect As String
    a = 0
    b = 2
    icount = 2
      ListBox1.Clear                                                                        'Cancello tutti dati precedenti
           ListBox1.ColumnCount = 8                                             'Imposto i titoli delle colonne
           ListBox1.ColumnHeads = False          
                topList = Array("Num.", "LUNEDI'", "MARTEDI'", "MERCOLEDI'", "GIOVEDI'", "VENERDI'", "SABATO", "DOMENICA")
                         With ListBox1
                               .Column() = topList
                         End With
 DBPath = "F:\DIARIO.xls"                                                           'Imposto la connessione al file EXCEL              
      sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
   Conn.Open sconnect
    sSQLSting = "SELECT * From [Calendario$]"
      mrs.Open sSQLSting, Conn
           For a = 1 To 12                                                                 'mediante un ciclo inserisco tutti i dati
                ListBox1.AddItem
                           ListBox1.List(icount - 1, 0) = mrs.Fields("Num.").Value
                           ListBox1.List(icount - 1, 1) = mrs.Fields("LUNEDI'").Value
                           ListBox1.List(icount - 1, 2) = mrs.Fields("MARTEDI'").Value
                           ListBox1.List(icount - 1, 3) = mrs.Fields("MERCOLEDI'").Value
                           ListBox1.List(icount - 1, 4) = mrs.Fields("GIOVEDI'").Value
                           ListBox1.List(icount - 1, 5) = mrs.Fields("VENERDI'").Value
                           ListBox1.List(icount - 1, 6) = mrs.Fields("SABATO").Value
                           ListBox1.List(icount - 1, 7) = mrs.Fields("DOMENICA").Value
                     icount = icount + 1                 
               mrs.MoveNext
        next a

Il problema è che prende tutti i dati cominciano sempre dalla prima riga del foglio EXCEL, quella sotto i titoli.

Io vorrei modificare il codice in modo da farlo iniziare da una riga diversa (p.es. la sesta, l'ottava, la decima, etc,.).

Come posso fare?

6 Risposte

  • Re: Controllo ListBox & inserisci dati

    Usa un Range

    sSQLSting = "SELECT * From [Calendario$A10:H50]"

    ad esempio

  • Re: Controllo ListBox & inserisci dati

    Grazie per la tua rapida risposta.

    Ho provato a correggere il codice come mi hai suggerito, così:

    On Error Resume Next
      Dim a As Long
      Dim b As Long
      Dim sSQLQry As String
      Dim ReturnArray
      Dim Conn As New ADODB.Connection
      Dim mrs As New ADODB.Recordset
      Dim icount As Long
      Dim DBPath As String, sconnect As String
        a = 6
        b = 2
        icount = 2
          ListBox1.Clear
          ListBox1.ColumnCount = 8
          ListBox1.ColumnHeads = False
            topList = Array("Num.", "LUNEDI'", "MARTEDI'", "MERCOLEDI'", "GIOVEDI'", "VENERDI'", "SABATO", "DOMENICA")
              With ListBox1
                 .Column() = topList
              End With
     DBPath = "F:\DIARIO.xls"
          sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
       Conn.Open sconnect
        sSQLSting = "SELECT * From [Calendario$C10:I16]"
          mrs.Open sSQLSting, Conn   
              For a = 1 To 6         
                   ListBox1.AddItem
                        ListBox1.List( icount - 1, 0) = mrs.Fields("Num.").Value
                        ListBox1.List( icount - 1, 1) = mrs.Fields("LUNEDI'").Value
                        ListBox1.List( icount - 1, 2) = mrs.Fields("MARTEDI'").Value
                        ListBox1.List( icount - 1, 3) = mrs.Fields("MERCOLEDI'").Value
                        ListBox1.List( icount - 1, 4) = mrs.Fields("GIOVEDI'").Value
                        ListBox1.List( icount - 1, 5) = mrs.Fields("VENERDI'").Value
                        ListBox1.List( icount - 1, 6) = mrs.Fields("SABATO").Value
                        ListBox1.List( icount - 1, 7) = mrs.Fields("DOMENICA").Value
                     icount = icount + 1
                     b = b + 1               
                   mrs.MoveNext         
            Next a

    ma nel controllo ListBox non mi visualizza nulla.

  • Re: Controllo ListBox & inserisci dati

    Controlla il nome esatto dei campi.

    Metti uno Stop nel ciclo e vai nella finestra immediata e scrivi

    Print mrs.Fields(0).Name

  • Re: Controllo ListBox & inserisci dati

    Ciao,

    la soluzione proposta da oregon è corretta e funziona benissimo:

    Per esempio, poniamo di avere un file excel con questi dati e si vuole leggere il range "A16:H20":

    allora basterà inserire nella stringa sql il range di celle:             Dim cmd As New OleDbCommand("SELECT * FROM [Data001$A16:H20]", conn)

    e in questo esempio si ottiene :

    Imports System.Data.OleDb
    
    Public Class FormExcelSqlImport
    
        ' LOAD FORM
        Private Sub FormExcelSqlImport_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ' Load listview with data from excel file
            MyLoadListExcelRange()
        End Sub
        
        ' LOAD EXCEL FILE IN LISTVIEW
        Sub MyLoadListExcelRange()
    
            ' Clear ListView
            ListViewExcel.Clear()
            ' Set columns name and width 
            Dim colonne As String() = {"Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"}
            ListViewExcel.Columns.Add("Num.", 40, HorizontalAlignment.Left)
            For Each col In colonne
                ListViewExcel.Columns.Add(col, 100, HorizontalAlignment.Left)
            Next
    
            ' Path excel file
            Dim stringFullPath As String = "C:\xxxxxxxxxxxxxxxxx\TestCnnSqlOld.xls"
            ' Set connection string
            Dim connStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & stringFullPath & ";Extended Properties='Excel 8.0;HDR=YES;'"
    
            '  Open connection
            Using conn As New OleDbConnection(connStr)
                conn.Open()
                ' Execute string sql command
                Dim cmd As New OleDbCommand("SELECT * FROM [Data001$A16:H20]", conn)
                Dim reader As OleDbDataReader = cmd.ExecuteReader()
    
                ' Reader data
                While reader.Read()
                    ' Set the first value as the main item and add subitems
                    Dim item As New ListViewItem(reader(0).ToString())
                    For i As Integer = 1 To 7
                        item.SubItems.Add(reader(i).ToString())
                    Next
                    ' Add the item to the ListView
                    ListViewExcel.Items.Add(item)
                End While
    
                ' Close reader
                reader.Close()
            End Using
        End Sub
    
    End Class
  • Re: Controllo ListBox & inserisci dati

    Ma se si volesse leggere da una certa riga in poi fino alla fine del foglio excel, allora si potrebbe fare una cosa semplice semplice di questo tipo:

    Poniamo di voler leggere dalla riga 18 fino alla fine del foglio...

    Passiamo per esempio il parametro della riga = a 18 per richiamare il metodo :          MyLoadListExcel(18)

    Imports System.Data.OleDb
    
    Public Class FormExcelSqlImport
    
        ' LOAD FORM
        Private Sub FormExcelSqlImport_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ' Load listview with data from excel file
            MyLoadListExcel(18)
        End Sub
    
        ' LOAD EXCEL FILE IN LISTVIEW
        Sub MyLoadListExcel(startRow As Integer)
    
            ' Clear ListView
            ListViewExcel.Clear()
            ' Set columns name and width 
            Dim colonne As String() = {"Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"}
            ListViewExcel.Columns.Add("Num.", 40, HorizontalAlignment.Left)
            For Each col In colonne
                ListViewExcel.Columns.Add(col, 100, HorizontalAlignment.Left)
            Next
    
            ' Path excel file
            Dim stringFullPath As String = "C:\xxxxxxxxxxxxxxxxxxxxx\TestCnnSqlOld.xls"
            ' Set connection string
            Dim connStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & stringFullPath & ";Extended Properties='Excel 8.0;HDR=YES;'"
    
            '  Open connection
            Using conn As New OleDbConnection(connStr)
                conn.Open()
                ' Execute string sql command
                Dim cmd As New OleDbCommand("SELECT * FROM [Data001$]", conn)
                Dim reader As OleDbDataReader = cmd.ExecuteReader()
    
                ' Set current row number
                Dim currentRow As Integer = 1
    
                ' Reader data
                While reader.Read()
                    ' Check row number read
                    If currentRow >= startRow Then
                        ' Set the first value as the main item and add subitems
                        Dim item As New ListViewItem(reader(0).ToString())
                        For i As Integer = 1 To 7
                            item.SubItems.Add(reader(i).ToString())
                        Next
                        ' Add the item to the ListView
                        ListViewExcel.Items.Add(item)
                    End If
                    ' Increment row number
                    currentRow += 1
                End While
    
                ' Close reader
                reader.Close()
            End Using
        End Sub
    
    End Class

    e si ottiene :

  • Re: Controllo ListBox & inserisci dati

    Fare sempre attenzione, sia se si passa un range oppure un numero di riga iniziale,  da dove partono i dati da leggere come da impostazione nella stringa di connessione:

    ' Set connection string
    Dim connStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & stringFullPath & ";Extended Properties='Excel 8.0;HDR=YES;'"
    

    dove nel parametro HDR=YES si indica se leggere o meno la riga di intestazione del foglio excel.

    Nota:

    Negli esempi sopra riportati ho adottato una ListView e una connessione per le vecchie versioni di office excel... ma il concetto, per quanto riguarda la stringa sql e la lettura delle righe, non cambia.

Devi accedere o registrarti per scrivere nel forum
6 risposte