Search code examples
pythonexcelpywinauto

How could I close Excel file using pywinauto


I'm having a problem that I can't excel file.

I was using swapy+pywinauto.
program export excel file with different name (ex. time..) I used swapy to close the export excel.

from pywinauto.application import Application
app = Application().Start(cmd_line=u'"C:\\Program Files\\Microsoft Office\\Office14\\EXCEL.EXE" \\dde')
xlmain = app.XLMAIN
xlmain.Wait('ready')
xlmain.Close()
app.Kill_()

but got error below.

Traceback (most recent call last):


 File "D:/23007.py", line 54, in <module>
xlmain.Wait('ready')

WaitUntil(timeout, retry_interval, lambda: self.__check_all_conditions(check_method_names))


File "C:\Python35\lib\site-packages\pywinauto\timings.py", line 308, in WaitUntil
raise err

pywinauto.timings.TimeoutError: timed out

Process finished with exit code 1

enter image description here


Solution

  • Why do you use app.XLMAIN? Is the title of window similar to XLMAIN? Usually the title is <file name> - Excel so that pywinauto can handle it so: xlmain = app["<file name> - Excel"].

    Obviously Wait('ready') raised an exception because the window with title "XLMAIN" or similar is not found.

    Generally I would recommend using pyWin32 standard module win32com.client to work with Excel (through standard COM interface). See the second answer here for example: Driving Excel from Python in Windows