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
|
import win32com.client as win32
import time
import os
class Office_work:
""" Class to work on word and excel with win32"""
# Class constant definition for pywin32
wdReplaceNone=0
wdReplaceOne=1
wdReplaceAll=2
wdFindContinue=1
wdAllowOnlyFormFields=2
NoReset=True
#pour close/save :
wdDoNotSaveChanges=0
wdSaveChanges=-1
wdCharacter=1
wdCell=12
wdLine=5
wdAlignLeft=0
wdAlignCenter=1
wdAlignRight=2
def __init__(self,file_name):
""" connect to word or excel doc """
self.file_name=file_name
self.type_file=self.file_name[-4:].upper() # "DOCX" or "XLSX" or "XLSM"
if self.type_file=="DOCX":
self.w = win32.Dispatch('Word.Application') # Start of word
self.w.Visible = False # File no visible
self.doc = self.w.Documents.Open(file_name) # word doc open
if self.type_file in ["XLSX","XLSM"] :
self.w = win32.Dispatch('Excel.Application') # start of excel
self.w.Visible = False # File no visible
self.doc = self.w.Workbooks.Open(file_name) # xlsx doc open
time.sleep(1)
def replace_all(self, oldchaine, newchaine=''):
"""
oldchaine = string to replace
newchaine = string for replace
"""
if self.type_file=="DOCX":
sel = self.w.Selection
sel.ClearFormatting()
sel.Find.Text = oldchaine
sel.Find.Forward = True
newchaine=newchaine.replace('\n','\r')
try :
sel.Find.Execute( oldchaine,False,False,False,False,False,True,self.wdFindContinue,False,newchaine,self.wdReplaceAll)
except:
pass
self.position=sel
elif self.type_file in ["XLSX","XLSM"] :
for sh in self.w.Sheets:
sh.Cells(5000,5000).Value=oldchaine # not clean but oblige to do that, if not => error message if no change..
try:
sh.Cells.Replace(oldchaine, newchaine)
except:
pass
sh.Cells(5000,5000).Value=None
def save_close_file(self):
self.doc.Save() # to save to other file, the syntax is self.doc.SaveAs(self.new_file_name)
self.doc.Close(0, 1) # 0 = No change, 1 = original format
self.w.Application.Quit() # To quit application
def start_file(self):
os.startfile(self.file_name)
file_name=r"C:\python\test.docx"
d=Office_work(file_name)
d.replace_all(" "," ")
d.replace_all("\r\r","\r")
d.save_close_file()
d.start_file() |
Partager