python - 使用 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
任何建议在这里
解决方案
在开始之前,请确保您的路径是正确的。如果您使用的是 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
推荐阅读
- javascript - 当我不想调用 Django 视图时,它被调用了——为什么?
- python - 谷歌云功能以并行运行不同用户参数的相同训练作业
- rust - 异常返回el1后无法使用堆栈指针
- sql - 为什么 o.id(primary_key) 和 o.account_id(Foreign_key) 之间存在输出差异?
- mysql - 在查询中获取错误的 COUNT 值
- android - 使用多级 IntDef 来描述数据的固定结构以提高效率
- sql - 案例否定列
- text - 在输入中将部分文本更改为不同的颜色
- python-3.x - 使用用户的输入从多个文件中选择代码将在哪个 csv 文件上运行(python pandas)
- python - 如何用 bs4 刮下一个标签