Bonjour à tous,

J'utilise PyWin 32 pour manipuler des fichiers word et en particulier le script ci-dessous que j'ai eu le bonheur de trouver:


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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# -*- coding: cp1252 -*-
 
#
# by Michel Claveau Informatique
# http://mclaveau.com
#
 
try: import psyco; psyco.full() 
except: pass
import time
from win32com.client import Dispatch
 
 
GlobalPVersion='1.5'
 
 
class word(object):
 
    wdReplaceNone=0
    wdReplaceOne=1
    wdReplaceAll=2
    wdFindContinue=1
 
    #pour close/save :
    wdDoNotSaveChanges=0
    wdSaveChanges=-1
 
    wdCharacter=1
    wdCell=12
    wdLine=5
 
    wdAlignLeft=0
    wdAlignCenter=1
    wdAlignRight=2
 
 
 
    def __init__(self, fichier=None, visible=True):
        import win32com.client
        import time
        self.w=win32com.client.Dispatch('Word.Application')
        if fichier!=None:
            time.sleep(0)
            self.open(fichier, visible)
 
 
 
    def u1252(self, chu):
        try: 
            if type(chu) is unicode:
                return chu.encode('cp1252','replace')
            else:
                return chu
        except:
            return repr(chu)
 
 
    def open(self, fichier, visible=True):
        """Ouvre un document word
        """
        self.doc=self.w.Documents.Open(fichier)
        self.visible(visible)
 
 
    def close(self):
        """ferme le document, en sauvegardant, sans demander
        """
        self.w.ActiveDocument.Close(SaveChanges = self.wdDoNotSaveChanges)
 
 
    def saveas(self,fichier, typ=0):
        """Appel de 'Enregistrer sous', avec le nom du fichier
 
           wdFormatDocument=0           # format Word. Valeur par défaut. 
           wdFormatTemplate=1           # modèle Word
           wdFormatText=2               # texte sans mise en forme (ANSI)
           wdFormatTextLineBreaks=3     # texte sans mise en forme
           wdFormatDOSText=4            # texte sans mise en forme (ANSI) 
           wdFormatDOSTextLineBreaks=5  # texte sans mise en forme, mais avec sauts de ligne.
           wdFormatRTF=6                # RTF
           wdFormatUnicodeText=7        # texte_Unicode/texte_Encodé. Paramètre supplémentaire pour l'encodage.
           wdFormatHTML=8               # HTML
        """
        self.doc.SaveAs(fichier, typ)
 
 
    def quit(self):
        """Ferme word
        """
        self.w.Quit()
 
 
    def quitSaveChange(self):
        """Ferme word, en sauvant les changements
        """
        self.w.Quit(self.wdSaveChanges)
 
 
    def quitCancel(self):
        """Ferme word, SANS sauver les changements
        """
        self.w.Quit(self.wdDoNotSaveChanges)
 
 
    def visible(self, par=True):
        """Rend Word visible (True), ou invisible (False) ; True par défaut
        Note : c'est plus rapide en invisible
        """
        if par:
            self.w.Visible=True
        else:
            self.w.Visible=False
 
 
    def hide(self):
        """Cache Word
        """
        self.w.visible=False
 
 
    def wprint(self):
        """Imprime le document
        """
        self.doc.PrintOut()
 
 
    def preview(self):
        """Pré-visualise le document
        """
        self.doc.PrintPreview()
 
 
    def previewclose(self):
        """Ferme la prévisdualisation du document
        """
        self.doc.ClosePrintPreview()
 
 
    def text(self, txt):
        """Remplace le texte sélectionné, par le paramètre
        """
        newchaine=txt.replace('\n','\r')
        self.position.Text = newchaine
 
 
    def TypeText(self, chaine):
        """ 'Tape' le texte à la position courante
        """
        self.position.TypeText(chaine)
 
 
    def chSelect(self, chchaine):
        """Sélectionne (recherche) la chaine passée en paramètre
        """
        sel = self.w.Selection
        sel.ClearFormatting()
        sel.Find.Text = chchaine
        sel.Find.Forward = True
        sel.Find.Execute()
        self.position=sel
        sel.Select()
 
 
    def macroRun(self, name):
        """Lance la macro-word (VBA) 'name'
        """
        self.w.Run(name)
 
 
    def language(self):
        """Retourne la langue de Word, ainsi que le code-langue de word
        """
        id=self.w.LanguageSettings.LanguageID(2)
        if id==1078	:  l="Afrikaans"
	elif id==1052	:  l="Albanian"
	elif id==14337	:  l="Arabic - United Arab Emirates"
	elif id==15361	:  l="Arabic - Bahrain"
	elif id==5121	:  l="Arabic - Algeria"
	elif id==3073	:  l="Arabic - Egypt"
	elif id==2049	:  l="Arabic - Iraq"
	elif id==11265	:  l="Arabic - Jordan"
	elif id==13313	:  l="Arabic - Kuwait"
	elif id==12289	:  l="Arabic - Lebanon"
	elif id==4097	:  l="Arabic - Libya"
	elif id==6145	:  l="Arabic - Morocco"
	elif id==8193	:  l="Arabic - Oman"
	elif id==16385	:  l="Arabic - Qatar"
	elif id==1025	:  l="Arabic - Saudi Arabia"
	elif id==10241	:  l="Arabic - Syria"
	elif id==7169	:  l="Arabic - Tunisia"
	elif id==9217	:  l="Arabic - Yemen"
	elif id==1067	:  l="Armenian"
	elif id==1068	:  l="Azeri - Latin"
	elif id==2092	:  l="Azeri - Cyrillic"
	elif id==1069	:  l="Basque"
	elif id==1059	:  l="Belarusian"
	elif id==1026	:  l="Bulgarian"
	elif id==1027	:  l="Catalan"
	elif id==2052	:  l="Chinese - China"
	elif id==3076	:  l="Chinese - Hong Kong SAR"
	elif id==5124	:  l="Chinese - Macau SAR"
	elif id==4100	:  l="Chinese - Singapore"
	elif id==1028	:  l="Chinese - Taiwan"
	elif id==1050	:  l="Croatian"
	elif id==1029	:  l="Czech"
	elif id==1030	:  l="Danish"
	elif id==1043	:  l="Dutch - The Netherlands"
	elif id==2067	:  l="Dutch - Belgium"
	elif id==3081	:  l="English - Australia"
	elif id==10249	:  l="English - Belize"
	elif id==4105	:  l="English - Canada"
	elif id==9225	:  l="English - Caribbean"
	elif id==6153	:  l="English - Ireland"
	elif id==8201	:  l="English - Jamaica"
	elif id==5129	:  l="English - New Zealand"
	elif id==13321	:  l="English - Phillippines"
	elif id==7177	:  l="English - South Africa"
	elif id==11273	:  l="English - Trinidad"
	elif id==2057	:  l="English - United Kingdom"
	elif id==1033	:  l="English - United States"
	elif id==1061	:  l="Estonian"
	elif id==1065	:  l="Farsi"
	elif id==1035	:  l="Finnish"
	elif id==1080	:  l="Faroese"
	elif id==1036	:  l="French - France"
	elif id==2060	:  l="French - Belgium"
	elif id==3084	:  l="French - Canada"
	elif id==5132	:  l="French - Luxembourg"
	elif id==4108	:  l="French - Switzerland"
	elif id==2108	:  l="Gaelic - Ireland"
	elif id==1084	:  l="Gaelic - Scotland"
	elif id==1031	:  l="German - Germany"
	elif id==3079	:  l="German - Austria"
	elif id==5127	:  l="German - Liechtenstein"
	elif id==4103	:  l="German - Luxembourg"
	elif id==2055	:  l="German - Switzerland"
	elif id==1032	:  l="Greek"
	elif id==1037	:  l="Hebrew"
	elif id==1081	:  l="Hindi"
	elif id==1038	:  l="Hungarian"
	elif id==1039	:  l="Icelandic"
	elif id==1057	:  l="Indonesian"
	elif id==1040	:  l="Italian - Italy"
	elif id==2064	:  l="Italian - Switzerland"
	elif id==1041	:  l="Japanese"
	elif id==1042	:  l="Korean"
	elif id==1062	:  l="Latvian"
	elif id==1063	:  l="Lithuanian"
	elif id==1071	:  l="FYRO Macedonian"
	elif id==1086	:  l="Malay - Malaysia"
	elif id==2110	:  l="Malay – Brunei"
	elif id==1082	:  l="Maltese"
	elif id==1102	:  l="Marathi"
	elif id==1044	:  l="Norwegian - Bokmål"
	elif id==2068	:  l="Norwegian - Nynorsk"
	elif id==1045	:  l="Polish"
	elif id==2070	:  l="Portuguese - Portugal"
	elif id==1046	:  l="Portuguese - Brazil"
	elif id==1047	:  l="Raeto-Romance"
	elif id==1048	:  l="Romanian - Romania"
	elif id==2072	:  l="Romanian - Moldova"
	elif id==1049	:  l="Russian"
	elif id==2073	:  l="Russian - Moldova"
	elif id==1103	:  l="Sanskrit"
	elif id==3098	:  l="Serbian - Cyrillic"
	elif id==2074	:  l="Serbian - Latin"
	elif id==1074	:  l="Setsuana"
	elif id==1060	:  l="Slovenian"
	elif id==1051	:  l="Slovak"
	elif id==1070	:  l="Sorbian"
	elif id==1034	:  l="Spanish - Spain"
	elif id==11274	:  l="Spanish - Argentina"
	elif id==16394	:  l="Spanish - Bolivia"
	elif id==13322	:  l="Spanish - Chile"
	elif id==9226	:  l="Spanish - Colombia"
	elif id==5130	:  l="Spanish - Costa Rica"
	elif id==7178	:  l="Spanish - Dominican Republic"
	elif id==12298	:  l="Spanish - Ecuador"
	elif id==4106	:  l="Spanish - Guatemala"
	elif id==18442	:  l="Spanish - Honduras"
	elif id==2058	:  l="Spanish - Mexico"
	elif id==19466	:  l="Spanish - Nicaragua"
	elif id==6154	:  l="Spanish - Panama"
	elif id==10250	:  l="Spanish - Peru"
	elif id==20490	:  l="Spanish - Puerto Rico"
	elif id==15370	:  l="Spanish - Paraguay"
	elif id==17418	:  l="Spanish - El Salvador"
	elif id==14346	:  l="Spanish - Uruguay"
	elif id==8202	:  l="Spanish - Venezuela"
	elif id==1072	:  l="Sutu"
	elif id==1089	:  l="Swahili"
	elif id==1053	:  l="Swedish - Sweden"
	elif id==2077	:  l="Swedish - Finland"
	elif id==1097	:  l="Tamil"
	elif id==1092	:  l="Tatar"
	elif id==1054	:  l="Thai"
	elif id==1055	:  l="Turkish"
	elif id==1073	:  l="Tsonga"
	elif id==1058	:  l="Ukrainian"
	elif id==1056	:  l="Urdu"
	elif id==2115	:  l="Uzbek - Cyrillic"
	elif id==1091	:  l="Uzbek – Latin"
	elif id==1066	:  l="Vietnamese"
	elif id==1076	:  l="Xhosa"
	elif id==1085	:  l="Yiddish"
	elif id==1077	:  l="Zulu"
        return l
 
 
    def filterTxt(self):
        """Convertit une sélection en texte
        """
        ss=self.u1252(self.w.Selection.Text)
	ss=ss.replace(chr(7)+chr(13),'   ')
        ss=ss.replace(chr(13),'\r\n')
	ss=ss.replace(chr(7),' ')
	ss=ss.replace(chr(9),'')
	ss=ss.replace(chr(26),'')
	return ss
 
 
    def eSelAll(self):
        """sélectionne, et retourne, tout le document
        """
        sel=self.w.Selection.WholeStory()
        return self.filterTxt()
 
 
    def eSelWord(self, nb=1):
        """étend la sélection aux nb mots à droite, et retourne la sélection
        """
        self.w.Selection.MoveRight(self.wdWord, nb, self.wdExtend)
        return self.filterTxt()
 
 
    def eSelLine(self, nb=1):
        """étend la sélection aux nb lignes en-dessous, et retourne la sélection
        """
        self.w.Selection.MoveDown(self.wdLine, nb, self.wdExtend)
        return self.filterTxt()
 
 
    def eSelEndLine(self):
        """étend la sélection jusqu'à la fin de la ligne, et retourne la sélection
        """
        self.w.Selection.EndKey(self.wdLine, self.wdExtend)
        return self.filterTxt()
 
 
    def chRemplAll(self, oldchaine, newchaine=''):
        """
        oldchaine = chaine a remplacer / string to replace
        newchaine = chaine de remplacement / string for replace
        """
        sel = self.w.Selection
        sel.ClearFormatting()
        sel.Find.Text = oldchaine
        sel.Find.Forward = True
        newchaine=newchaine.replace('\n','\r')
        sel.Find.Execute( oldchaine,False,False,False,False,False,True,self.wdFindContinue,False,newchaine,self.wdReplaceAll)
        self.position=sel
 
 
    def chRemplOne(self, oldchaine, newchaine=''):
        """
        oldchaine = chaine a remplacer / string to replace
        newchaine = chaine de remplacement / string for replace
        """
        sel = self.w.Selection
        sel.ClearFormatting()
        sel.Find.Text = oldchaine
        sel.Find.Forward = True
        newchaine=newchaine.replace('\n','\r')
        sel.Find.Execute( oldchaine,False,False,False,False,False,True,self.wdFindContinue,False,newchaine,self.wdReplaceOne)
        self.position=sel
 
 
    def chRemplClipboard(self, oldchaine):
        """
        oldchaine = chaine a remplacer / string to replace
        """
        sel = self.w.Selection
        sel.ClearFormatting()
        sel.Find.Text = oldchaine
        sel.Find.Forward = True
 
        sel.Find.Execute( oldchaine,False,False,False,False,False,True,self.wdFindContinue,False,'XXX',self.wdReplaceOne)
        sel.Paste()
        self.position=sel
 
 
    def chRemplGraf(self, oldchaine, fichier):
        """
        oldchaine = chaine a remplacer / string to replace
        """
        sel = self.w.Selection
        sel.ClearFormatting()
        sel.Find.Text = oldchaine
        sel.Find.Forward = True
 
        sel.Find.Execute( oldchaine,False,False,False,False,False,True,self.wdFindContinue,False,'',self.wdReplaceOne)
        sel.InlineShapes.AddPicture(fichier, False, True)
        self.position=sel
 
 
    def TableauInsLigApres(self, oldchaine, nblig=1):
        """
        oldchaine = chaine a remplacer / string to replace
        """
        sel = self.w.Selection
        sel.ClearFormatting()
        sel.Find.Text = oldchaine
        sel.Find.Forward = True
 
        sel.Find.Execute( oldchaine,False,False,False,False,False,True,self.wdFindContinue,False,'',self.wdReplaceOne)
        sel.InsertRowsBelow(nblig)
 
 
    def TableauDelLig(self, oldchaine):
        """
        oldchaine = chaine a remplacer / string to replace
        """
        sel = self.w.Selection
        sel.ClearFormatting()
        sel.Find.Text = oldchaine
        sel.Find.Forward = True
 
        sel.Find.Execute( oldchaine,False,False,False,False,False,True,self.wdFindContinue,False,'',self.wdReplaceOne)
        sel.Rows.Delete()
 
 
    def MoveRight(self, nb=1):
        self.position.MoveRight(self.wdCharacter, nb)
 
 
    def MoveLeft(self, nb=1):
        self.position.MoveLeft(self.wdCharacter, nb)
 
 
    def TableauMoveRight(self, nb=1):
        sel = self.w.Selection
        sel.MoveRight(self.wdCell, nb)
 
 
    def TableauMoveLeft(self, nb=1):
        sel = self.w.Selection
        sel.MoveLeft(self.wdCell, nb)
 
 
    def TableauMoveLine(self, nb=1):
        sel = self.w.Selection
        if nb>0:
            sel.MoveDown(self.wdLine, nb)
        else:
            sel.MoveUp(self.wdLine, -nb)
 
 
    def TableauCellule(self, lig=1, col=1, txt='', align=0):
        tbl = self.doc.Tables[0]
        cellule = tbl.Cell(lig, col)
        cellule.Range.Text = txt 
        cellule.Range.ParagraphFormat.Alignment = align  #0,1,2, left, center, right
 
 
    def landscape(self):
        """Met le document en mode paysage
        """
        self.wdOrientLandscape=1
        self.wdOrientPortrait=0
        self.w.ActiveDocument.PageSetup.Orientation = self.wdOrientLandscape 
 
 
    def portrait(self):
        """Met le document en mode portrait
        """
        self.wdOrientLandscape=1
        self.wdOrientPortrait=0
        self.w.ActiveDocument.PageSetup.Orientation = self.wdOrientPortrait 
 
 
    def changePrinter(self, printerName):
        """Change l'imprimante active de Word
        """
        self.w.ActivePrinter = printerName
 
 
#if __name__=='__main__':
    #pass
Lorsque je souhaite utiliser
J'ai l'erreure suivante que se produit parfois:
Traceback (most recent call last):
File "C:\pyinstaller1_4\atellconf_1\hmi_ppe_noyee.py", line 568, in export
select_chemin()
File "C:\pyinstaller1_4\atellconf_1\hmi_ppe_noyee.py", line 560, in select_chemin
export_word(chemin)
File "C:\pyinstaller1_4\atellconf_1\hmi_ppe_noyee.py", line 495, in export_word
self.sortie.chRemplAll('.SITUATION_EXPLOITANT.', str(self.txt1.GetValue()))
File "C:\pyinstaller1_4\atellconf_1\word.py", line 360, in chRemplAll
sel.Find.Execute( oldchaine,False,False,False,False,False,True,self.wdFindContinue,False,newchaine,self.wdReplaceAll)
File "<COMObject <unknown>>", line 8, in Execute
pywintypes.com_error: (-2147352567, "Une exception s'est produite.", (0, u'Microsoft Word', u'Param\xe8tre de la cha\xeene trop long.', u'C:\\Program Files\\Microsoft Office\\OFFICE11\\1036\\wdmain11.chm', 25334, -2146822434), None)
A priori j'ai un souci de longueur de chaine, car ce problème n'apparait qu'à partir d'un certain nombre de caractères... (non défini à l'heure actuelle).

Quelqu'un a-t-il déjà rencontré ce problème et si oui comment l'a-t-il résolui autrement que de compter le nombre de caractères du texte à écrire et de diviser en autant de portions que nécessaire.

D'avance merci