首页 > 解决方案 > 使用 Python 刷新 Excel - 出现错误

问题描述

我正在尝试刷新 excel,因为我在其中使用了数据透视数据。但我收到错误

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

current_dir = Path.cwd()
out_file = current_dir.joinpath(destination_file)
print(f"The outfile path is {out_file}")

# Open the workbook in said instance of Excel
wb_7 = xlapp.workbooks.open(out_file)

# Refresh all data connections.
wb_7.RefreshAll()
wb_7.Save()

# Quit
xlapp.Quit()

错误是

 wb_7 = xlapp.workbooks.open(out_file)
 File "<COMObject <unknown>>", line 2, in open
 TypeError: must be real number, not WindowsPath

任何建议在这里

标签: pythonwin32com

解决方案


在开始之前,请确保您的路径是正确的。如果您使用的是 jupyter notebook,它会引发错误。如果您的 excel 文件与 py 脚本位于同一文件夹中,则应使用以下代码分配路径:

pathname = os.path.dirname(sys.argv[0])
path = os.path.abspath(pathname) + '\\'
out_file = path + out_file

此外,您需要适当地使用该功能。有些函数以大写字母开头。使用如下:

xlapp.Workbooks.Open

为了健康提神,我建议您打开具有特定属性的 xlapp,例如:

xlapp = win32com.client.gencache.EnsureDispatch("Excel.Application")
xlapp.Interactive = False
xlapp.Application.EnableEvents = False
xlapp.DisplayAlerts = False  # Suppress any Alert windows, which require User action
xlapp.AskToUpdateLinks = False # Disable automatic update linking
xlapp.Visible = False  # Run the Application in the background

清爽

wb_7 = xlapp.Workbooks.Open(out_file)
wb_7.RefreshAll()
xlapp.CalculateUntilAsyncQueriesDone()
wb_7.Save()
wb_7.Close(True)
wb_7 = None   # Unset wb_7 variable (This is to ensure it's closed)

并且不要忘记恢复原始的excel属性

xlapp.Interactive = True
xlapp.DisplayAlerts = True  # Suppress any Alert windows, which require User action
xlapp.AskToUpdateLinks = True  # Disable automatic update linking
xlapp.Application.EnableEvents = True
xlapp.Visible = True  # Run the Application in the background
xlapp.Quit()    # Close Excel

推荐阅读