打开excel文件从python中的相对文件路径运行宏

2024-09-29 02:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中运行如下代码来打开excel并运行宏。基本上我的python脚本就在其中

C:\Users\adrlee\Desktop\Python files\Automation

以及我的excel VBA文件(自动化.xlsb)坐在里面

^{pr2}$

我在运行这个代码

fileDir = os.path.dirname(os.path.realpath('__file__'));

filename = os.path.join(fileDir, '../Powerpoint/Automation.xlsb')
filename = os.path.abspath(os.path.realpath(filename))
print(filename);

if os.path.exists("Powerpoint/Automation.xlsb"):
    xl=win32com.client.Dispatch("Excel.Application")
    xl.Workbooks.Open(filename)
    xl.Application.Quit() # Comment this out if your excel script closes
    del xl

print("Powerpoint generated");

但我错了

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Sorry, we couldn't find C:\\Users\\adrlee\\Desktop\\Python files\\Powerpoint\\Automation.xlsb. Is it possible it was moved, renamed or deleted?", 'xlmain11.chm', 0, -2146827284), None)

我做错什么了


Tags: path代码osfilesfilenameexcelusersautomation
2条回答

如果fileDir包含

C:\Users\adrlee\Desktop\Python files\Automation\

然后将..\Powerpoint\Automation.xlsb连接到它将得到

^{pr2}$

相当于

C:\Users\adrlee\Desktop\Python files\Powerpoint\Automation.xlsb

因为..相当于父目录,...\Python files\Automation的父目录是...\Python files。在


你的问题说明Excel文件实际上

C:\Users\adrlee\Desktop\Python files\Automation\Powerpoint\Automation.xlsb

所以您应该将.\Powerpoint\Automation.xlsb连接到fileDir变量。(当..表示父目录时,.表示现有目录。)

即使用:

filename = os.path.join(fileDir, './Powerpoint/Automation.xlsb')

谢谢各位的评论和提示!我终于做到了:

fileDir = os.path.dirname(os.path.realpath('__file__'));

filename = os.path.join(fileDir, './Powerpoint/Funnel Automation.xlsb')
print(filename);


xl=win32com.client.Dispatch('Excel.Application')
xl.Workbooks.Open(Filename = filename)
del xl

print("Powerpoint generated");

相关问题 更多 >