refresh.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import zipfile
  2. import xlwings
  3. import win32com.client
  4. from pathlib import Path
  5. def refresh(filename_str: str):
  6. filename = Path(filename_str)
  7. if not filename.exists():
  8. print("!! Error: File does not exist !!")
  9. return
  10. if filename.name.endswith(".xls"):
  11. return refresh_old(filename)
  12. return refresh_new(filename)
  13. def refresh_old(xls_file: Path):
  14. print(f"Refresh '{xls_file.resolve()}'")
  15. excel = win32com.client.Dispatch("Excel.Application")
  16. excel.DisplayAlerts = False
  17. workbook = excel.Workbooks.Open(xls_file.resolve())
  18. try:
  19. for source in workbook.LinkSources(1):
  20. print(" --> " + source)
  21. if Path(source).exists():
  22. excel.Workbooks.Open(source)
  23. else:
  24. print(" !! does not exist !!")
  25. except TypeError:
  26. print(" --> " + "no LinkSources")
  27. workbook.RefreshAll()
  28. workbook.Save()
  29. workbook.Close(True)
  30. excel.Application.Quit()
  31. def refresh_new(xlsx_file: Path):
  32. print(f"Refresh '{xlsx_file.resolve()}'")
  33. try:
  34. excel = xlwings.App(visible=False)
  35. workbook = xlwings.Book(xlsx_file, update_links=False)
  36. except zipfile.BadZipFile as e:
  37. print(e)
  38. return
  39. try:
  40. for source in workbook.api.LinkSources():
  41. print(" --> " + source)
  42. if Path(source).exists():
  43. xlwings.Book(source, update_links=False, read_only=True)
  44. else:
  45. print(" !! does not exist !!")
  46. except TypeError:
  47. print(" --> " + "no LinkSources")
  48. workbook.api.RefreshAll()
  49. workbook.save()
  50. workbook.close()
  51. excel.quit()