save_all.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. '''Created 8 Aug 2023 Levi'''
  2. from datetime import datetime
  3. from time import (time, gmtime, strftime)
  4. import win32com.client
  5. wb_to_save = {'2020 havi forgalom.xlsx', 'HR_SYS_2021.xlsm', 'Finance_no_refresh.xlsm'}
  6. def time_it(func):
  7. def wrapper(*args, **kwargs):
  8. start = time()
  9. result = func(*args, **kwargs)
  10. end = time()
  11. mlsec = repr(end - start).split('.')[1][:3]
  12. elapsed = strftime(f"%M:%S.{mlsec}", gmtime(end - start))
  13. print(f'{func.__name__} finished in {elapsed}')
  14. return result
  15. return wrapper
  16. @time_it
  17. def save_all_open_workbooks():
  18. try:
  19. # Create a new instance of the Excel application
  20. excel_app = win32com.client.Dispatch('Excel.Application')
  21. # Set visible to False to hide Excel during the process
  22. excel_app.Visible = True
  23. # Get the Workbooks collection
  24. workbooks = excel_app.Workbooks
  25. # Save each workbook
  26. for wb in workbooks:
  27. if wb.Name in wb_to_save:
  28. wb.Save()
  29. print(f'saving {wb.Name}')
  30. print('All open workbooks saved successfully.', datetime.now().strftime('%d-%m-%Y %H:%M:%S'))
  31. except Exception as e:
  32. print(f'Error occurred: {e}')
  33. # finally:
  34. # # Quit Excel application
  35. # # excel_app.Quit()
  36. # pass
  37. if __name__ == '__main__':
  38. save_all_open_workbooks()