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

PyQt Python Discussion :

Ouverture et ecriture d'un fichier excel depuis Pyqt


Sujet :

PyQt Python

  1. #1
    Membre du Club
    Homme Profil pro
    Inscrit en
    Août 2011
    Messages
    57
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Août 2011
    Messages : 57
    Points : 46
    Points
    46
    Par défaut Ouverture et ecriture d'un fichier excel depuis Pyqt
    Bonjour,

    Je teins tout d'abord à dire que je débute avec Pyqt...

    J'avais réalisé en son temps une pettite application qui me permettais de rentrer des données dans un fichier excel via un GUI Tkinter dont voici un exemple de code:
    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
    # -*- coding: UTF-8 -*-
     
    # Importation des modules graphiques
    from Tkinter import *
    import tkFont
     
    #Imporation des modules système
    import win32com.client as win32
    import win32com.client.dynamic
    from pywintypes import UnicodeType, TimeType
    import os
     
     
    def Validation():
        DEFAULT = 0.00
        DEFAULTSTR = ""
        aDossier = str(NumeroHydrobru.get()or DEFAULTSTR)
        aProjet = str(NomProjet.get() or DEFAULTSTR)
        aCumul = float(LongCumul.get()or DEFAULT)
     
        #=================================================
        """ DANS LA FEUILLE (CALCUL) """
        #=================================================
        sht = xls.Worksheets('Calcul')
        sht.Activate()
     
        sht.Cells(9,8).Value = aDossier
        sht.Cells(11,8).Value = aProjet
        sht.Cells(13,8).Value = aCumul
     
     
    Mafenetre= Tk()
    Mafenetre.title('test excel')
    Mafenetre.configure(padx = 10, pady = 10)
    Mafenetre.resizable(True,  True)
    police=tkFont.Font(Mafenetre, weight = 'bold',  size = '10' )
    police1=tkFont.Font(Mafenetre, weight = 'bold',  size = '12' )
     
    # Démarrage excel
    excel = win32com.client.dynamic.Dispatch('Excel.Application')
     
    # Ouverture du fichier pour édition
    xls = excel.Workbooks.Open ('E:\TRAVAIL\test_1.xls')
    excel.Visible = True
     
    # Création des labels ect...
    Dossier = Label(Mafenetre, text = 'Entrez le numéro de dossier : ',  font = police)
    Dossier.grid(row = 0, column = 0, pady = 5, padx= 20, sticky = 'W')
    NumeroHydrobru = Entry(Mafenetre , width = 20,  font = police)
    NumeroHydrobru.grid(row = 0, column = 1)
    Projet = Label(Mafenetre, text = 'Entrez le nom de votre projet : ',  font = police)
    Projet.grid(row = 0, column = 3, pady = 5, padx = 20, sticky = 'W')
    NomProjet = Entry(Mafenetre , width = 20,  font = police)
    NomProjet.grid(row = 0, column = 4)
    Cumul = Label(Mafenetre, text = "Entrez la longueur : ",  font = police)
    Cumul.grid(row = 0, column = 6, pady = 5, padx = 10, sticky = 'W')
    LongCumul = Entry(Mafenetre , width = 20,  font = police)
    LongCumul.grid(row = 0, column = 7)
    Metre = Label(Mafenetre, text = "M", font = police)
    Metre.grid(row = 0, column = 8, sticky = 'W')
     
    #===============================================================================
    #
    #                           BOUTON DE VALIDATION
    #
    #===============================================================================
     
    valide = Button (Mafenetre,
                     font = police1,
                     bd = 6,
                     bg = 'alice blue',
                     text = 'VALIDER',
                     relief = RAISED, command = Validation
                    )
     
    valide.grid (row= 1, column = 0, pady = 25, sticky = "E")
    valide.bind('<Return>', Validation)
    #===============================================================================
     
    Mafenetre.mainloop()
    Ca fonctionne très bien, aussi, j'aurais voulu transposer ce code vers une application PyQt4, j'ai donc essayé avec le code suivant:
    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
    # -*- coding: utf-8 -*-
    from PyQt4.QtGui import *
    from PyQt4.QtCore import *
    import os, sys
    from untitled import *
    import win32com.client as win32
    import win32com.client.dynamic
    from pywintypes import UnicodeType, TimeType
     
     
    class entree(QtGui.QDialog):
      def __init__(self, parent=None):
        super(entree, self).__init__(parent)
        self.setLayout(QtGui.QGridLayout())
     
        self.lab_NumDos = QtGui.QLabel(self.tr("Entrez le numéro de dossier :"))
        self.lab_NumProj = QtGui.QLabel("Entrez le numéro de projet:")
        self.lab_Longueur = QtGui.QLabel("Entrez la longueur :")
        self.entry_NumDos = QtGui.QLineEdit()
        self.entry_NumProj = QtGui.QLineEdit()
        self.entry_Longueur = QtGui.QLineEdit()
     
     
        widg_but = QtGui.QWidget()
        widg_but.setLayout(QtGui.QHBoxLayout())
        self.but_ok = QtGui.QPushButton('Valider')
        self.but_ko = QtGui.QPushButton('Annuler')
        widg_but.layout().addStretch()
        widg_but.layout().addWidget(self.but_ok)
        widg_but.layout().addWidget(self.but_ko)
        widg_but.layout().addStretch()
     
     
        self.layout().addWidget(self.lab_NumDos,0,0)
        self.layout().addWidget(self.entry_NumDos,0,1)
        self.layout().addWidget(self.lab_NumProj,1,0)
        self.layout().addWidget(self.entry_NumProj,1,1)
        self.layout().addWidget(self.lab_Longueur,2,0)
        self.layout().addWidget(self.entry_Longueur,2,1)
        self.layout().addWidget(widg_but,3,0,1,2)
     
        self.connect(self.but_ok,
                            SIGNAL("clicked()"),
                            self.valide);
     
        self.connect(self.but_ko,
                         SIGNAL("clicked()"),
                         QtCore.SLOT('close()'));
     
      def valide(self):
            DEFAULT = 0.00
            DEFAULTINT = 0
            DEFAULTSTR = ""
            aDossier = self.entry_NumDos.text()
            aProjet = self.entry_NumProj.text()
            aCumul = self.entry_Longueur.text()
     
            """
            print aDossier      |
            print aProjet       |-Ca ca fonctionne...
            print aCumul        |
            """
     
            # Démarrage excel
            excel = win32com.client.dynamic.Dispatch('Excel.Application')
     
            # Ouverture du fichier pour édition
            xls = excel.Workbooks.Open ('E:\TRAVAIL\test_1.xls')
            excel.Visible = True
            sht = xls.Worksheets('Calcul')
            sht.Activate()
            sht.Cells(9,8).Value = aDossier
            sht.Cells(11,8).Value = aProjet
            sht.Cells(13,8).Value = aCumul
     
    if __name__=='__main__':
      import sys
      app=QtGui.QApplication(sys.argv)
      fen = entree()
      fen.show()
      sys.exit(app.exec_())
    Mais là, si la fenêtre s'affiche bien et si j'enregistre bien les valeurs des QLineEdit, losqu'il s'agit d'ouvrir et d'écrire le fichier excel, j'ai le message d'erreur suivant:
    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
    Traceback (most recent call last):
      File "<string>", line 73, in execInThread
      File "E:\LiberKey\MyApps\python\App\lib\site-packages\rpyc\core\netref.py", line 196, in __call__
        return syncreq(_self, consts.HANDLE_CALL, args, kwargs)
      File "E:\LiberKey\MyApps\python\App\lib\site-packages\rpyc\core\netref.py", line 71, in syncreq
        return conn.sync_request(handler, oid, *args)
      File "E:\LiberKey\MyApps\python\App\lib\site-packages\rpyc\core\protocol.py", line 431, in sync_request
        self.serve(0.1)
      File "E:\LiberKey\MyApps\python\App\lib\site-packages\rpyc\core\protocol.py", line 379, in serve
        data = self._recv(timeout, wait_for_lock = True)
      File "E:\LiberKey\MyApps\python\App\lib\site-packages\rpyc\core\protocol.py", line 337, in _recv
        data = self._channel.recv()
      File "E:\LiberKey\MyApps\python\App\lib\site-packages\rpyc\core\channel.py", line 50, in recv
        header = self.stream.read(self.FRAME_HEADER.size)
      File "E:\LiberKey\MyApps\python\App\lib\site-packages\rpyc\core\stream.py", line 166, in read
        raise EOFError(ex)
    EOFError: [Errno 10054] An existing connection was forcibly closed by the remote host
    Mon fichier excel s'ouvre bien, mais les valeur ne sont pas encodée et l'app se ferme
    Je me doute qu'il s'agit d'un problème de thread, mais je sèche sur la manière d'obtenir mon résultat.
    Aussi, si je pouvais obtenir un petit coup de pouce...

    Merci d'avance,
    Pierre

  2. #2
    Membre régulier
    Homme Profil pro
    Inscrit en
    Mai 2013
    Messages
    89
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2013
    Messages : 89
    Points : 91
    Points
    91
    Par défaut
    Ma réponse ne vas pas d'être d'une grande utilité pour ton problème mais je me disais pourquoi coder une nouvelle appli en PyQT4 alors qu'il serait plus judicieux de la coder en PyQt5 vu que nous sommes en pleine periode de transition ?

  3. #3
    Membre du Club
    Homme Profil pro
    Inscrit en
    Août 2011
    Messages
    57
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Août 2011
    Messages : 57
    Points : 46
    Points
    46
    Par défaut
    Je dirais parce que je suis encore en Python 2.7, pour des raisons de bibliothèques...
    Je code parfois sous python 3, mais je ne compte y passer définitivement que lorsque la disponibilité des bibli sera satisfaisante.

  4. #4
    Membre habitué
    Profil pro
    Inscrit en
    Août 2009
    Messages
    195
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Août 2009
    Messages : 195
    Points : 156
    Points
    156
    Par défaut
    Bonjour


    Welcome dans le monde PyQt!

    ton code semble clair
    dans ta fonction valide
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    aDossier = self.entry_NumDos.text()
    aDossier est de type QString, pas une str.

    essaie ceci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    sht.Cells(9,8).Value = str(aDossier)
    J'espère que ça ira

  5. #5
    Membre du Club
    Homme Profil pro
    Inscrit en
    Août 2011
    Messages
    57
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Août 2011
    Messages : 57
    Points : 46
    Points
    46
    Par défaut
    Merci !
    Ca fonctionne parfaitement maintenant

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [AC-2000] Ouverture d'un fichier Excel depuis VBA Access
    Par Aeltith dans le forum VBA Access
    Réponses: 2
    Dernier message: 19/06/2010, 15h43
  2. Ouverture fichier excel depuis une servlet
    Par cecjahan dans le forum Servlets/JSP
    Réponses: 0
    Dernier message: 08/09/2008, 14h03
  3. Réponses: 1
    Dernier message: 05/09/2008, 13h05
  4. comment fermer un fichier Excel depuis Access?
    Par audrey_desgres dans le forum Access
    Réponses: 14
    Dernier message: 21/06/2005, 12h43
  5. Ouvrir un fichier excel depuis access
    Par ptitegrenouille dans le forum Macros et VBA Excel
    Réponses: 11
    Dernier message: 03/05/2005, 11h47

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