IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

Extraction de donne excel


Sujet :

Python

  1. #1
    Membre éclairé Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Par défaut Extraction de donne excel
    Problème dans ce code simpliste

    je cherche a extraire les données des colonnes N°2 et N°3.

    La première partie fonctionne sans aucun problème.
    La seconde partie de génère qu'un seul fichier , hors elle est basée sur le même processus algorithmique.
    Les deux colonnes ont exactement le même nombre de ligne contenant de données.
    L'erreur est probablement grossière , trop pour que puisse la voir
    Donc si vous avez une idée de correction je suis preneur

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    import xlrd
    
    
    if __name__ == '__main__':
    # ouverture du fichier Excel 
        wb = xlrd.open_workbook('XmlAllerRetour.xlsx')
        
        lignedb = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
        lignedb = lignedb + '\n' +'<soapenv:Body>'
        lignefn = '\n' +'</soapenv:Body>'
        lignefn = lignefn + '\n' + '</soapenv:Envelope>'
        
     
    # renvoie les noms des feuilles du fichier sous forme de liste.
        liste_feuille = wb.sheet_names() 
     
        feuille  = wb.sheet_by_index(0) # feuileN°1
        liste_feuille = feuille.col(1) # contenu de la colonne N°2 type cell
        nb_ligne = feuille.nrows  # le nombre de lignes  
        numcas = 0
        for lesdata in liste_feuille:
            nomfic ='NUMCAS_'+ str(numcas) + '.xml'
            numcas =numcas+1
            # Ouverture du fichier destination
            if lesdata.value !=  'VIDE':
                destination = open(nomfic, "w")
                ligneecrire =  lignedb + lesdata.value + lignefn
                destination.write(ligneecrire )
            # Fermeture du fichier destination
                destination.close()
                
        liste_feuille_r = feuille.col(2)
        numcas = 0
        for lesdata in liste_feuille_r:
            nomficRT ='NUMCAS_'+ str(numcas) + 'Retour.xml'
              # Ouverture du fichier destination
            des2 = open(nomficRT, "w")
            des2.write(lesdata.value)
               # Fermeture du fichier destination
            des2.close()
    

  2. #2
    Membre éclairé Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Par défaut Solution par une fonction
    Puisque la première partie fonctionne je suis passé par une fonction ce qui corrige le problème

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    # coding: utf-8  
    import xlrd
     
    def extracdata(liste_feuille  , type):
        numcas = 0
        if type ==  1:
            codenom ='in'
        else:
            codenom ='out'  
     
        for lesdata in liste_feuille:
            nomfic ='NUMCAS_'+ str(numcas) + codenom + '.xml'
            numcas = numcas + 1
            # Ouverture du fichier destination
            if lesdata.value !=  'VIDE':
                destination = open(nomfic, "w")
                ligneecrire =  lignedb + lesdata.value + lignefn
                destination.write(ligneecrire )
            # Fermeture du fichier destination
                destination.close()
        pass
     
    if __name__ == '__main__':
    # ouverture du fichier Excel 
        wb = xlrd.open_workbook('XmlAllerRetour.xlsx')
     
        lignedb = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
        lignedb = lignedb + '\n' +'<soapenv:Body>'
        lignefn = '\n' +'</soapenv:Body>'
        lignefn = lignefn + '\n' + '</soapenv:Envelope>'
     
    # renvoie les noms des feuilles du fichier sous forme de liste.
        liste_feuille = wb.sheet_names() 
     
        feuille  = wb.sheet_by_index(0) # feuile N°1
        la_feuille = feuille.col(1) # contenu de la colonne N°2 type cell
        nb_ligne = feuille.nrows  # le nombre de lignes 
         # traitement de la colonne N°1
        extracdata(la_feuille , 1)
        la_feuille_r = feuille.col(2)
        extracdata(la_feuille_r , 2)

  3. #3
    Membre éclairé Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Par défaut Nouvelle modification
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
     
    # coding: utf-8  
    import xlrd
    import xml.dom.minidom
     
    def SoapIn(docxml):
     
    #  lignedb = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
    # lignedb = '\n' + tab_4 + lignedb + '<soapenv:Body>'
    #  lignefn =  '\n' +' </soapenv:Body>'
    # lignefn = tab_4 + lignefn + '\n' + '</soapenv:Envelope>
        Soapenv_Envelope_ouvrant = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
        Soapenv_body_ouvrant =  '<soapenv:Body>'
        Soapenv_Envelope_fermante = ' </soapenv:Body>'
        Soapenv_body__fermante = '</soapenv:Envelope>'   
        rt_docxml = Soapenv_Envelope_ouvrant +  Soapenv_body_ouvrant + docxml + Soapenv_Envelope_fermante +   Soapenv_body__fermante
        return rt_docxml
     
    def SoapOut(docxml):
        Soap_Envelope_ouvrant = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
        Soap_body_ouvrant =  '<soap:Body>'
        Soap_Envelope_fermante = ' </soap:Body>'
        Soap_body__fermante = '</soap:Envelope>'   
        rt_docxml = Soap_Envelope_ouvrant +  Soap_body_ouvrant + docxml + Soap_Envelope_fermante + Soap_body__fermante
        return rt_docxml
     
     
     
    def extracdata(liste_feuille  , type):
        numcas = 0
        for lesdata in liste_feuille:
            numcas = numcas + 1
            # Ouverture du fichier destination
            if lesdata.value !=  'VIDE':  # construction des noms de fichier
                if type ==  1:
                    nomfic ='NUMCAS_'+ str(numcas) + '_in.xml'
                    ligneecrire= SoapIn(lesdata.value)
                else:
                    nomfic ='NUMCAS_'+ str(numcas) + '_out.xml'
                    ligneecrire= SoapOut(lesdata.value)
     
                # ecriture du fichier
                dom = xml.dom.minidom.parseString(ligneecrire) # convertie le text en arbre xml DOM
                 #dom_xml = dom.toxml()
                destination = open(nomfic, "w")
                dom_xml = dom.toprettyxml()
     
                destination.write(dom_xml)
                        # Fermeture du fichier destination
                destination.close()
        pass
     
    if __name__ == '__main__':
    # ouverture du fichier Excel 
        wb = xlrd.open_workbook('XmlAllerRetour.xlsx')
        tab_4 = '   '
     
    # renvoie les noms des feuilles du fichier sous forme de liste.
        liste_feuille = wb.sheet_names() 
     
        feuille  = wb.sheet_by_index(0) # feuile N°1
        la_feuille = feuille.col(1) # contenu de la colonne N°2 type cell
        nb_ligne = feuille.nrows  # le nombre de lignes 
         # traitement de la colonne N°1
        extracdata(la_feuille , 1)
        la_feuille_r = feuille.col(2)
        extracdata(la_feuille_r , 2)
    voila un petit formattage du code xml

  4. #4
    Membre éclairé Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Par défaut Problème d'acces a une cellue
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    # coding: utf-8  
     
    import xlrd
    import xml.dom.minidom
    import string
    import sys
    import os
    import datetime
    import tkinter 
    from tkinter.filedialog import askopenfilename
    
    '''
    Created on 21 aout 2017
    @author: moi 
    '''
    def explorateur_window(repertoireinit):
        """ Explorateur Windows    """
        root = tkinter.Tk()
    
        filename = tkinter.filedialog.askopenfilename(
            initialdir=repertoireinit,
            title="Choisir votre fichier",
            filetypes=(
                ("Fichier xlsx", "*.xlsx"),
                ("Tous type de fichier","*.*")
            )
        )
        return filename
    pass
    
    
    
    
    
    
    def SoapIn(docxml):
        
    #  lignedb = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
    # lignedb = '\n' + tab_4 + lignedb + '<soapenv:Body>'
    #  lignefn =  '\n' +' </soapenv:Body>'
    # lignefn = tab_4 + lignefn + '\n' + '</soapenv:Envelope>
        Soapenv_Envelope_ouvrant = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
        Soapenv_body_ouvrant =  '<soapenv:Body>'
        Soapenv_Envelope_fermante = ' </soapenv:Body>'
        Soapenv_body__fermante = '</soapenv:Envelope>'   
        rt_docxml = Soapenv_Envelope_ouvrant +  Soapenv_body_ouvrant + docxml + Soapenv_Envelope_fermante +   Soapenv_body__fermante
        return rt_docxml
    
    def SoapOut(docxml):
        Soap_Envelope_ouvrant = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
        Soap_body_ouvrant =  '<soap:Body>'
        Soap_Envelope_fermante = ' </soap:Body>'
        Soap_body__fermante = '</soap:Envelope>'   
        rt_docxml = Soap_Envelope_ouvrant +  Soap_body_ouvrant + docxml + Soap_Envelope_fermante + Soap_body__fermante
        return rt_docxml
    
                
    def LireExcel(fichier):
                # renvoie les noms des feuilles du fichier sous forme de liste.
        liste_feuille = fichier.sheet_names() 
    
        feuille  = fichier.sheet_by_index(0) # feuile N°1
        la_feuille = feuille.col(1) # contenu de la colonne N°2 type cell
        nb_ligne = feuille.nrows  # le nombre de lignes 
        #print(nb_ligne)
         # traitement de la colonne N°1
        extracdata(la_feuille , 1,feuille)
        la_feuille_r = feuille.col(2)
        extracdata(la_feuille_r , 2, feuille)
        pass
        
    def extracdata(liste_feuille  , type, feuille):
        numcas = 0
        for lesdata in liste_feuille:
            numcas = numcas + 1
            #myCell.value : rowInd, colInd  renvoie la valeur. 
            numdos  = feuille.cell.value(numcas, 5)
            
            
            print(numdos)
            # Ouverture du fichier destination
            if lesdata.value !=  'VIDE':  # construction des noms de fichier
                if type ==  1:
                    nomfic ='NUMCAS_'+ str(numcas) + '_in.xml'
                    ligneecrire= SoapIn(lesdata.value)
                else:
                    nomfic ='NUMCAS_'+ str(numcas) + '_out.xml'
                    ligneecrire= SoapOut(lesdata.value)
                 # Reconstute le nom du fichier   
                nom_fichier_path_out = os.path.join(nom_fichier_path, nomfic)        
    
                dom = xml.dom.minidom.parseString(ligneecrire) # convertie le text en arbre xml DOM
                dom_xml = dom.toprettyxml(indent="   ", newl="\n" ) # formattage XML soap
                 # Reconstute le nom du fichier   
                nom_fichier_path_out = os.path.join(nom_fichier_path, nomfic)                
                destination = open(nom_fichier_path_out , "w") # ouverture du fichier de sortie
      
                #dom_xml = dom.toprettyxml()
                destination.write(dom_xml)
                        # Fermeture du fichier destination
                destination.close()
               # convertieunix(nomfic)
        pass
    
    if __name__ == '__main__':
    # ouverture du fichier Excel 
        
        
        nom_fichier_path_in = explorateur_window ("C://") # Recherche via explorateur
        if os.path.isfile(nom_fichier_path_in):
            # ouverture du fichier
     
            wb = xlrd.open_workbook(nom_fichier_path_in)
            # Ouverture du fichier destination
     
            nom_fichier_in = os.path.basename(nom_fichier_path_in) # Retourne le dernier élément d'un chemin
            nom_fichier_path = os.path.dirname(nom_fichier_path_in) # Retourne le dossier parent de l'élément
            list_nf = os.path.split(nom_fichier_path_in) # Fractionne un chemin d'accès. Retourne un tuple
        try:
            if os.path.isfile(nom_fichier_path_in):       
                LireExcel(wb)     
                
        finally:
            print('Terminé')

    Je recherche a recupere dans ce code et a ce niveau du processus les données d'une cellule positionnée dans une autre collone de ma feuille .
    Je passe donc en attribut à ma fonction la référence de la feuille compléte .
    Je cherche comment en extraire de données a savoir la collone N°6 pour la ligne en cours de lecture dans la liste.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
        numdos  = feuille.cell.value(numcas, 5)
    voici ce que me renvoi l'application
    AttributeError: 'function' object has no attribute 'value'
    je ne trouve pas comment récupere les données de la cellule concernée


    source d'info http://www.python-simple.com/python-...dards/xlrd.php

  5. #5
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 695
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 695
    Par défaut
    Salut,

    Citation Envoyé par dedalios Voir le message
    je ne trouve pas comment récupère les données de la cellule concernée
    Dans le petit tuto. (que vous avez) mentionné, récupérer la valeur d'une cellule s'écrit mySheet.cell_value(5, 1) et non mySheet.cell.value(5, 1).

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  6. #6
    Membre éclairé Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Par défaut
    La version du code qui ne pause aucun problème.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    # coding: utf-8  
     
    import xlrd
    import xml.dom.minidom
    import string
    import sys
    import os
    import datetime
    import tkinter 
    from tkinter.filedialog import askopenfilename
     
    '''
    Created on 21 aout 2017
    @author: moi 
    '''
    def explorateur_window(repertoireinit):
        """ Explorateur Windows    """
        root = tkinter.Tk()
    #"Total-Flux_Non_Traitable_Flunet.txt"
        filename = tkinter.filedialog.askopenfilename(
            initialdir=repertoireinit,
            title="Choisir votre fichier",
            filetypes=(
                ("Fichier xlsx", "*.xlsx"),
                ("Tous type de fichier","*.*")
            )
        )
        return filename
    pass
     
     
    def SoapIn(docxml):
     
    #  lignedb = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
    # lignedb = '\n' + tab_4 + lignedb + '<soapenv:Body>'
    #  lignefn =  '\n' +' </soapenv:Body>'
    # lignefn = tab_4 + lignefn + '\n' + '</soapenv:Envelope>
        Soapenv_Envelope_ouvrant = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
        Soapenv_body_ouvrant =  '<soapenv:Body>'
        Soapenv_Envelope_fermante = ' </soapenv:Body>'
        Soapenv_body__fermante = '</soapenv:Envelope>'   
        rt_docxml = Soapenv_Envelope_ouvrant +  Soapenv_body_ouvrant + docxml + Soapenv_Envelope_fermante +   Soapenv_body__fermante
        return rt_docxml
     
    def SoapOut(docxml):
        Soap_Envelope_ouvrant = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
        Soap_body_ouvrant =  '<soap:Body>'
        Soap_Envelope_fermante = ' </soap:Body>'
        Soap_body__fermante = '</soap:Envelope>'   
        rt_docxml = Soap_Envelope_ouvrant +  Soap_body_ouvrant + docxml + Soap_Envelope_fermante + Soap_body__fermante
        return rt_docxml
     
     
    def LireExcel(fichier):
                # renvoie les noms des feuilles du fichier sous forme de liste.
        liste_feuille = fichier.sheet_names() 
     
        feuille  = fichier.sheet_by_index(0) # feuile N°1
        la_feuille = feuille.col(1) # contenu de la colonne N°2 type cell
        nb_ligne = feuille.nrows  # le nombre de lignes 
        #print(nb_ligne)
         # traitement de la colonne N°1
        extracdata(la_feuille , 1,feuille)
        la_feuille_r = feuille.col(2)
        extracdata(la_feuille_r , 2, feuille)
        pass
     
    def extracdata(liste_feuille , type, feuille):
        numcas = 0
        for lesdata in liste_feuille:
            numcas = numcas + 1
            #myCell.value : rowInd, colInd  renvoie la valeur. 
            print(numcas)
            numdos  = feuille.cell_value(numcas, 5)
            print(numdos)
            # Ouverture du fichier destination
            if lesdata.value !=  'VIDE':  # construction des noms de fichier
                if type ==  1:
                    nomfic ='NUMCAS_'+ str(numcas) + '_in.xml'
                    ligneecrire= SoapIn(lesdata.value)
                else:
                    nomfic ='NUMCAS_'+ str(numcas) + '_out.xml'
                    ligneecrire= SoapOut(lesdata.value)
                 # Reconstute le nom du fichier   
                nom_fichier_path_out = os.path.join(nom_fichier_path, nomfic)        
     
                dom = xml.dom.minidom.parseString(ligneecrire) # convertie le text en arbre xml DOM
                dom_xml = dom.toprettyxml(indent="   ", newl="\n" ) # formattage XML soap
                 # Reconstute le nom du fichier   
                nom_fichier_path_out = os.path.join(nom_fichier_path, nomfic)                
                destination = open(nom_fichier_path_out , "w") # ouverture du fichier de sortie
     
                #dom_xml = dom.toprettyxml()
                destination.write(dom_xml)
                        # Fermeture du fichier destination
                destination.close()
               # convertieunix(nomfic)
        pass
     
    if __name__ == '__main__':
    # ouverture du fichier Excel 
        rep ='C:\\'    
        nom_fichier_path_in = explorateur_window (rep) # Recherche via explorateur
        if os.path.isfile(nom_fichier_path_in):
            # ouverture du fichier
     
            wb = xlrd.open_workbook(nom_fichier_path_in)
            # Ouverture du fichier destination
     
            nom_fichier_in = os.path.basename(nom_fichier_path_in) # Retourne le dernier élément d'un chemin
            nom_fichier_path = os.path.dirname(nom_fichier_path_in) # Retourne le dossier parent de l'élément
            list_nf = os.path.split(nom_fichier_path_in) # Fractionne un chemin d'accès. Retourne un tuple
        try:
            if os.path.isfile(nom_fichier_path_in):       
                LireExcel(wb)     
     
        finally:
            print('Terminé')

    Voici la version modifiée avec la correction relative à la partie du code
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     numdos  = feuille.cell_value(numcas, 5)
    Si le premier code fonctionne, le second pause soucis.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    # coding: utf-8  
     
    import xlrd
    import xml.dom.minidom
    import string
    import sys
    import os
    import datetime
    import tkinter 
    from tkinter.filedialog import askopenfilename
     
    '''
    Created on 21 aout 2017
    @author: moi 
    '''
    def explorateur_window(repertoireinit):
        """ Explorateur Windows    """
        root = tkinter.Tk()
     
        filename = tkinter.filedialog.askopenfilename(
            initialdir=repertoireinit,
            title="Choisir votre fichier",
            filetypes=(
                ("Fichier xlsx", "*.xlsx"),
                ("Tous type de fichier","*.*")
            )
        )
        return filename
    pass
     
    def SoapIn(docxml):
        """ bloc soapui ouverture"""
    #  lignedb = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
    # lignedb = '\n' + tab_4 + lignedb + '<soapenv:Body>'
    #  lignefn =  '\n' +' </soapenv:Body>'
    # lignefn = tab_4 + lignefn + '\n' + '</soapenv:Envelope>
        Soapenv_Envelope_ouvrant = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
        Soapenv_body_ouvrant =  '<soapenv:Body>'
        Soapenv_Envelope_fermante = ' </soapenv:Body>'
        Soapenv_body__fermante = '</soapenv:Envelope>'   
        rt_docxml = Soapenv_Envelope_ouvrant +  Soapenv_body_ouvrant + docxml + Soapenv_Envelope_fermante +   Soapenv_body__fermante
        return rt_docxml
     
    def SoapOut(docxml):
        """ bloc soapui fermeture"""
        Soap_Envelope_ouvrant = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
        Soap_body_ouvrant =  '<soap:Body>'
        Soap_Envelope_fermante = ' </soap:Body>'
        Soap_body__fermante = '</soap:Envelope>'   
        rt_docxml = Soap_Envelope_ouvrant +  Soap_body_ouvrant + docxml + Soap_Envelope_fermante + Soap_body__fermante
        return rt_docxml
     
     
    def LireExcel(fichier):
     
        # renvoie les noms des feuilles du fichier sous forme de liste.
        liste_feuille = fichier.sheet_names() 
     
        feuille  = fichier.sheet_by_index(0) # feuile N�1
        la_feuille = feuille.col(1) # contenu de la colonne N�2 type cell
        nb_ligne = feuille.nrows  # le nombre de lignes 
        #print(nb_ligne)
         # traitement de la colonne N�1
        extracdata(la_feuille , 1,feuille)
        print("traitement type 1, terminer")
        la_feuille_r = feuille.col(2)
        print("extraction de la seconde colonne")
        extracdata(la_feuille_r , 2, feuille)
        print("traitement type 2, terminer")
        pass
     
    def extracdata(liste_feuille  , type, feuille):
        numcas = 0
        for lesdata in liste_feuille:
            numcas = numcas + 1
            #myCell.value : rowInd, colInd  renvoie la valeur. 
            numdos  = feuille.cell_value(numcas, 5)
            print(type)
            # Ouverture du fichier destination
            if lesdata.value !=  'VIDE':  # construction des noms de fichier
                if type ==  1:
                    nomfic ='NUMCAS_'+ str(numcas) + '_in.xml'
                    ligneecrire= SoapIn(lesdata.value)
                else:
                    nomfic ='NUMCAS_'+ str(numcas) + '_out.xml'
                    ligneecrire= SoapOut(lesdata.value)
                 # Reconstute le nom du fichier   
                nom_fichier_path_out = os.path.join(nom_fichier_path, nomfic)        
     
                dom = xml.dom.minidom.parseString(ligneecrire) # convertie le text en arbre xml DOM
                dom_xml = dom.toprettyxml(indent="   ", newl="\n" ) # formattage XML soap
                 # Reconstute le nom du fichier   
                nom_fichier_path_out = os.path.join(nom_fichier_path, nomfic)                
                destination = open(nom_fichier_path_out , "w") # ouverture du fichier de sortie
     
                #dom_xml = dom.toprettyxml()
                destination.write(dom_xml)
                        # Fermeture du fichier destination
                destination.close()
               # convertieunix(nomfic)
        pass
     
    if __name__ == '__main__':
    # ouverture du fichier Excel 
     
     
        nom_fichier_path_in = explorateur_window ("C://") # Recherche via explorateur
        if os.path.isfile(nom_fichier_path_in):
            # ouverture du fichier
     
            wb = xlrd.open_workbook(nom_fichier_path_in)
            # Ouverture du fichier destination
     
            nom_fichier_in = os.path.basename(nom_fichier_path_in) # Retourne le dernier �l�ment d'un chemin
            nom_fichier_path = os.path.dirname(nom_fichier_path_in) # Retourne le dossier parent de l'�l�ment
            list_nf = os.path.split(nom_fichier_path_in) # Fractionne un chemin d'acc�s. Retourne un tuple
        try:
            if os.path.isfile(nom_fichier_path_in):       
                LireExcel(wb)     
     
        finally:
            print('Termine')

    Mais problème. voici ce que donne le traitement.
    Les 2 colonnes lus sont similaires.

    1
    1
    1
    ....
    1
    Termine
    Traceback (most recent call last):
    File "C:\Users\ExtracteurExcel_6.py", line 119, in <module>
    LireExcel(wb)
    File "C:\Users\ExtracteurExcel_6.py", line 64, in LireExcel
    extracdata(la_feuille , 1,feuille)
    File "C:\Users\ExtracteurExcel_6.py", line 77, in extracdata
    numdos = feuille.cell_value(numcas, 5)
    File "C:\Python36\lib\site-packages\xlrd\sheet.py", line 409, in cell_value
    return self._cell_values[rowx][colx]
    IndexError: list index out of range[/QUOTE]

  7. #7
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 695
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 695
    Par défaut
    Salut,

    Si Python se vautre avec un IndexError, il a raison!
    Et vous devez vérifier par 3 fois que les données que vous lui donnez sont bien celles que vous pensez.
    "print", "len" sont des fonctions utiles pour répondre à ce genre de questions.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  8. #8
    Membre éclairé Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Par défaut Trace
    J'ai donc ajouté des traces selon les conseils des traces

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
           def LireExcel(fichier):
         # renvoie les noms des feuilles du fichier sous forme de liste.
        liste_feuille = fichier.sheet_names() 
    
        feuille  = fichier.sheet_by_index(0) # feuile N�1
        la_feuille = feuille.col(1) # contenu de la colonne N�2 type cell
        nb_ligne = feuille.nrows  # le nombre de lignes 
        #print(nb_ligne)
         # traitement de la colonne N�1
        print("traitement type 1, Debut")
        extracdata(la_feuille , 1,feuille)
        print("traitement type 1, terminer")
        
        la_feuille_r = feuille.col(2)
        print("extraction de la seconde colonne")
        extracdata(la_feuille_r , 2, feuille)
        print("traitement type 2, terminer")
        pass

    j'ai mais le code a problème en commentaire.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    def extracdata(liste_feuille  , type, feuille):
        numcas = 0
        for lesdata in liste_feuille:
            numcas = numcas + 1
            #myCell.value : rowInd, colInd  renvoie la valeur. 
            print(numcas)
            
            #numdos  = feuille.cell_value(numcas, 5)
         
            # Ouverture du fichier destination
            if lesdata.value !=  'VIDE':  # construction des noms de fichier
                if type ==  1:
                    nomfic ='NUMCAS_'+ str(numcas) + '_in.xml'
                    ligneecrire= SoapIn(lesdata.value)
                else:
                    nomfic ='NUMCAS_'+ str(numcas) + '_out.xml'
                    ligneecrire= SoapOut(lesdata.value)
                 # Reconstitu le nom du fichier   
                nom_fichier_path_out = os.path.join(nom_fichier_path, nomfic)        
    
                dom = xml.dom.minidom.parseString(ligneecrire) # convertie le text en arbre xml DOM
                dom_xml = dom.toprettyxml(indent="   ", newl="\n" ) # formattage XML soap
                 # Reconstitu le nom du fichier   
                nom_fichier_path_out = os.path.join(nom_fichier_path, nomfic)                
                destination = open(nom_fichier_path_out , "w") # ouverture du fichier de sortie
      
                #dom_xml = dom.toprettyxml()
                destination.write(dom_xml)
                        # Fermeture du fichier destination
                destination.close()
               # convertieunix(nomfic)
        pass
    traitement type 1, Debut
    1
    2
    3
    ...
    37
    38
    traitement type 1, terminer
    extraction de la seconde colonne
    1
    2
    3
    ...
    37
    38
    traitement type 2, terminer
    Termine


    Hors sans le commentaire

    traitement type 1, Debut
    1
    2
    3
    ..
    36
    37
    38
    Termine
    Traceback (most recent call last):
    File "C:\Users\ExtracteurExcel_6.py", line 121, in <module>
    LireExcel(wb)
    File "C:\Users\ExtracteurExcel_6.py", line 64, in LireExcel
    extracdata(la_feuille , 1,feuille)
    File "C:\Users\ExtracteurExcel_6.py", line 79, in extracdata
    numdos = feuille.cell_value(numcas, 5)
    File "C:\Python36\lib\site-packages\xlrd\sheet.py", line 409, in cell_value
    return self._cell_values[rowx][colx]
    IndexError: list index out of range

    il semble que les informations
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     numdos  = feuille.cell_value(38, 5)
    provoque list index out of range. Ce qui est curieux c'est que le derniers fichiers écrit est le 37.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    numcas =0
    for lesdata in liste_feuille:
            numcas = numcas + 1
    Le problème dans la boucle for, lorsque l'on entre dans boucle pour le dernière enregistrement , numcas =>38
    il refuse d’exécuté la commande
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     numdos  = feuille.cell_value(38, 5)
    dans un fichier excel il y a plus de 38 lignes... comme l'interprétation peut poser problème? Qu'en bien même cette cellule serait vide.....

  9. #9
    Membre éclairé Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Par défaut Corrrection de extracdata
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
        
    def extracdata(liste_feuille  , type, feuille):
    
        for lesdata in liste_feuille:
    
            #myCell.value : rowInd, colInd  renvoie la valeur. 
            numcas = liste_feuille.index(lesdata)
            #print(numcas)
            numdos  = feuille.cell_value(numcas, 5)
            
            # Ouverture du fichier destination
            if lesdata.value !=  'VIDE':  # construction des noms de fichier
                if type ==  1:
                    nomfic ='NUMCAS_'+ str(numcas) + '_in.xml'
                    ligneecrire= SoapIn(lesdata.value)
                else:
                    nomfic ='NUMCAS_'+ str(numcas) + '_out.xml'
                    ligneecrire= SoapOut(lesdata.value)
                 # Reconstitu le nom du fichier   
                nom_fichier_path_out = os.path.join(nom_fichier_path, nomfic)        
    
                dom = xml.dom.minidom.parseString(ligneecrire) # convertie le text en arbre xml DOM
                dom_xml = dom.toprettyxml(indent="   ", newl="\n" ) # formattage XML soap
                 # Reconstitu le nom du fichier   
                nom_fichier_path_out = os.path.join(nom_fichier_path, nomfic)                
                destination = open(nom_fichier_path_out , "w") # ouverture du fichier de sortie
      
                #dom_xml = dom.toprettyxml()
                destination.write(dom_xml)
                        # Fermeture du fichier destination
                destination.close()
               # convertieunix(nomfic)
    
        pass
    avec l'index de liste on éviter les mauvaises surprises

Discussions similaires

  1. Extraction de données Excel
    Par L'HeureuxDEbxl dans le forum Access
    Réponses: 3
    Dernier message: 02/04/2014, 19h17
  2. Solution pour Extraction de données Excell ? Routines?
    Par ccbbrr172 dans le forum Alimentation
    Réponses: 8
    Dernier message: 28/03/2008, 15h37
  3. extraction de données excel
    Par gzanax dans le forum Excel
    Réponses: 2
    Dernier message: 13/03/2007, 14h41
  4. Réponses: 23
    Dernier message: 01/03/2007, 15h03
  5. Extraction de données sur des fichiers excel
    Par iupgeii dans le forum MFC
    Réponses: 3
    Dernier message: 23/01/2004, 13h53

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo