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 :

Générer un fichier doc à partir d'un modèle XML


Sujet :

Python

  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    162
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 162
    Par défaut Générer un fichier doc à partir d'un modèle XML
    Bonjour,
    Je suis débutant en python et j'ai pour premier projet de maîtriser la lib pywin32 et minidom.
    j'ai pour objectif de créer un script me permettant de parser un fichier XML et à partir du DOM récupéré, ensuite générer un tableau dans un document word avec les donnés parsées.
    J'ai commencé un bout de script pour ouvrir un fichier word et écrire dedans.
    Je coince sur la partie XML car avec j'ai une erreur "invalide syntaxe" sur print xmlTag

    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
     
    from xml.dom.minidom import parse, parseString
    import win32com.client as win32
     
    #open the xml file for reading:
    file = open('C:\chemin\tableau.xml','r')
    #convert to string:
    data = file.read()
    #close file because we dont need it anymore:
    file.close()
    #parse the xml you got from the file
    dom = parseString(data)
    #retrieve the first xml tag (<tag>data</tag>) that the parser finds with name tagName:
    xmlTag = dom.getElementsByTagName('client')[0].toxml()
    #strip off the tag (<tag>data</tag>  --->   data):
    xmlData=xmlTag.replace('<client>','').replace('</client>','')
     
    #print out the xml tag and data in this format: <tag>data</tag>
    print xmlTag
    #just print the data
    print xmlData
     
    def word():
        word = win32.gencache.EnsureDispatch('Word.Application')
        doc = word.Documents.Add()
        word.Visible = True
        sleep(1)
     
        rng = doc.Range(0,0)
        rng.InsertAfter('Hacking Word with Python\r\n\r\n')
        rng.InsertAfter("\r\nPython rules!\r\n")
     
        #doc.Close(False)
        #word.Application.Quit()
     
    if __name__ == '__main__':
        word()

  2. #2
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par Hellgast Voir le message
    Bonjour,
    Je suis débutant en python et j'ai pour premier projet de maîtriser la lib pywin32 et minidom.
    j'ai pour objectif de créer un script me permettant de parser un fichier XML et à partir du DOM récupéré, ensuite générer un tableau dans un document word avec les donnés parsées.
    J'ai commencé un bout de script pour ouvrir un fichier word et écrire dedans.
    Je coince sur la partie XML car avec j'ai une erreur "invalide syntaxe" sur print xmlTag

    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
     
    from xml.dom.minidom import parse, parseString
    import win32com.client as win32
     
    #open the xml file for reading:
    file = open('C:\chemin\tableau.xml','r')
    #convert to string:
    data = file.read()
    #close file because we dont need it anymore:
    file.close()
    #parse the xml you got from the file
    dom = parseString(data)
    #retrieve the first xml tag (<tag>data</tag>) that the parser finds with name tagName:
    xmlTag = dom.getElementsByTagName('client')[0].toxml()
    #strip off the tag (<tag>data</tag>  --->   data):
    xmlData=xmlTag.replace('<client>','').replace('</client>','')
     
    #print out the xml tag and data in this format: <tag>data</tag>
    print xmlTag
    #just print the data
    print xmlData
     
    def word():
        word = win32.gencache.EnsureDispatch('Word.Application')
        doc = word.Documents.Add()
        word.Visible = True
        sleep(1)
     
        rng = doc.Range(0,0)
        rng.InsertAfter('Hacking Word with Python\r\n\r\n')
        rng.InsertAfter("\r\nPython rules!\r\n")
     
        #doc.Close(False)
        #word.Application.Quit()
     
    if __name__ == '__main__':
        word()
    Bonjour,

    Python2 : https://docs.python.org/2.7/library/...ons.html#print

    Python3 : https://docs.python.org/3.4/library/...ons.html#print

    Tout dépend de la version du langage que vous utilisez.

    @+.

  3. #3
    Expert confirmé

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 307
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 307
    Par défaut
    Salut,

    Tu utilises une syntaxe Python 2, avec Python 3 print est une fonction, donc il faut mettre l'argument entre parenthèses.

  4. #4
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 741
    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 741
    Par défaut
    Salut,

    Si vous ne montrez pas l'erreur, on peut se prendre la tête pour rien...
    Mais on peut aussi rester dans le trivial:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    >>> print xmlTag
      File "<stdin>", line 1
        print xmlTag
                   ^
    SyntaxError: invalid syntax
    >>>
    Mais il est improbable que la version de Python ait changé depuis que vous avez écrit ce script, çà ne devrait pas beaucoup aider.

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

  5. #5
    Membre confirmé
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    162
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 162
    Par défaut
    Du coup j'ai modifié en conséquence (je ne savais pas que les syntaxe différaient entre les versions)
    Niveau d'avancement :
    • Je parse partiellement mes données
    • J'arrive à créer un doc word avec un tableau

    Existe t-il un moyen plus efficace pour parser les données d'un fichier XML que les fonctions dom.getElementsByTagName et replace ?


    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
    from xml.dom.minidom import parse, parseString
    import win32com.client as win32
     
    def parseData():
        document = """\
        <client name="testn1">
            test 1
        </client>
        """
        dom = parseString(document)
        xmlTag = dom.getElementsByTagName('client')[0].toxml()
        xmlData=xmlTag.replace('<client (...) >','').replace('</client>','')
     
        print (xmlData)
     
    def getText(nodelist):
        rc = []
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
        return ''.join(rc)
     
    def rgb_to_hex(rgb):
        strValue = '%02x%02x%02x' % rgb
        iValue = int(strValue, 16)
        return iValue
     
    def word():
        word = win32.gencache.EnsureDispatch('Word.Application')
        worddoc = word.Documents.Add()
        word.Visible = True
     
        worddoc.PageSetup.Orientation = 1 
        worddoc.PageSetup.BookFoldPrinting = 1 
        worddoc.Content.Font.Size = 11
        worddoc.Content.Paragraphs.TabStops.Add (100)
        worddoc.Content.Text = "Hello, I am a text!"
     
        location = worddoc.Range()
        location.Collapse(1)
        location.Paragraphs.Add()
        location.Collapse(1)
     
        table = location.Tables.Add (location, 2, 3)
        table.ApplyStyleHeadingRows = 1
        table.AutoFormat(16)
     
        table.Cell(1,1).Range.InsertAfter("affaire")
        table.Cell(1,2).Range.InsertAfter("Date d'échéance")
        table.Cell(1,3).Range.InsertAfter("Client")
     
        #doc.Close(False)
        #word.Application.Quit()
     
    if __name__ == '__main__':
        parseData()
    résultat du parse :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    <client name="testn1">
            test 1

  6. #6
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par Hellgast Voir le message
    Du coup j'ai modifié en conséquence (je ne savais pas que les syntaxe différaient entre les versions)
    Niveau d'avancement :
    • Je parse partiellement mes données
    • J'arrive à créer un doc word avec un tableau

    Existe t-il un moyen plus efficace pour parser les données d'un fichier XML que les fonctions dom.getElementsByTagName et replace ?


    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
    from xml.dom.minidom import parse, parseString
    import win32com.client as win32
     
    def parseData():
        document = """\
        <client name="testn1">
            test 1
        </client>
        """
        dom = parseString(document)
        xmlTag = dom.getElementsByTagName('client')[0].toxml()
        xmlData=xmlTag.replace('<client (...) >','').replace('</client>','')
     
        print (xmlData)
     
    def getText(nodelist):
        rc = []
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
        return ''.join(rc)
     
    def rgb_to_hex(rgb):
        strValue = '%02x%02x%02x' % rgb
        iValue = int(strValue, 16)
        return iValue
     
    def word():
        word = win32.gencache.EnsureDispatch('Word.Application')
        worddoc = word.Documents.Add()
        word.Visible = True
     
        worddoc.PageSetup.Orientation = 1 
        worddoc.PageSetup.BookFoldPrinting = 1 
        worddoc.Content.Font.Size = 11
        worddoc.Content.Paragraphs.TabStops.Add (100)
        worddoc.Content.Text = "Hello, I am a text!"
     
        location = worddoc.Range()
        location.Collapse(1)
        location.Paragraphs.Add()
        location.Collapse(1)
     
        table = location.Tables.Add (location, 2, 3)
        table.ApplyStyleHeadingRows = 1
        table.AutoFormat(16)
     
        table.Cell(1,1).Range.InsertAfter("affaire")
        table.Cell(1,2).Range.InsertAfter("Date d'échéance")
        table.Cell(1,3).Range.InsertAfter("Client")
     
        #doc.Close(False)
        #word.Application.Quit()
     
    if __name__ == '__main__':
        parseData()
    résultat du parse :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    <client name="testn1">
            test 1
    Bonjour,

    Si vous faites essentiellement de l'extraction de données à partir de XML, peut-être serait-il plus judicieux d'utiliser la librairie xml.etree.ElementTree (ET) ?

    Doc xml.etree : https://docs.python.org/3/library/xm...ementtree.html

    Doc dom.minidom : https://docs.python.org/3/library/xml.dom.minidom.html

    @+.

  7. #7
    Membre confirmé
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    162
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 162
    Par défaut
    Merci des réponses je vais éplucher la doc de minidom en particulier

Discussions similaires

  1. Générer un fichier xls à partir d'un modèle xlt
    Par Peanut dans le forum Macros et VBA Excel
    Réponses: 1
    Dernier message: 27/01/2010, 10h21
  2. [VB]Générer un fichier Postscript à partir d'un pdf avec VB
    Par Vince dans le forum VB 6 et antérieur
    Réponses: 7
    Dernier message: 20/09/2005, 19h00
  3. créer un fichier rtf à partir d'un modèle
    Par petitelulu dans le forum Documents
    Réponses: 3
    Dernier message: 20/09/2005, 09h38
  4. Comment générer un fichier texte à partir d'un XML et XSL
    Par Jayceblaster dans le forum XSL/XSLT/XPATH
    Réponses: 1
    Dernier message: 24/07/2005, 22h42
  5. Réponses: 4
    Dernier message: 02/05/2005, 20h25

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