简体   繁体   中英

Python Script to refresh all excel files in a folder

I am trying to automate some of my work. I want to refresh all excel files in a specific folder. Below is the script that I tried.

```
import win32com.client
import glob2
from pathlib import Path

xlapp = win32com.client.DispatchEx("Excel.Application")

directory = 'Y:\\path\\to\directory'

pathlist = Path(directory).glob('*.xlsx')

for path in pathlist:
    wb = xlapp.Workbooks.Open(path)
    wb.RefreshAll()
    xlapp.CalculateUntilAsyncQueriesDone()
    xlapp.DisplayAlerts = False
    wb.Save()
    xlapp.Quit()

The above script refreshes the first excel file and then throws an error.
Error : Object invoked disconnected from its clients.

You close client in loop xlapp.Quit() .

May solve issue.

import win32com.client
import glob2
from pathlib import Path

xlapp = win32com.client.DispatchEx("Excel.Application")

directory = 'Y:\\path\\to\directory'

pathlist = Path(directory).glob('*.xlsx')

for path in pathlist:
    wb = xlapp.Workbooks.Open(path)
    wb.RefreshAll()
    xlapp.CalculateUntilAsyncQueriesDone()
    xlapp.DisplayAlerts = False
    wb.Save()

xlapp.Quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM