Search code examples
pythonexcelreplacepywin32

Interacting with Excel using pywin32


I have an easy task - iterate over a list of excel files and replace all occurencies of some words with other words.

Can't find out how it could be made using pywin32 library. Namely I can't find any clear documentation or examples how to interact with excel.

I want to iterate all sheets in excel doc and replace '111' with '222'.

I'm using the following code:

def searchexcel():
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    excel.Visible = False
    for infile in glob.glob( os.path.join('', '*.xls') ):
        print infile
        e = excel.Workbooks.Open(os.getcwd()+'\\'+infile)
        sh = e.Sheets()
        for sheet in e:
            sheet.Replace('111', '222', win32.constants.xlWhole)
        e.Save()
    excel.Application.Quit()

But it does not work properly.


Solution

  • As it was posted in comment, I should use sheet.Cells.Replace