[英]Open excel file to run macro from relative file path in python
I am running a code as below in python to open an excel and run a macro. 我在python中运行以下代码以打开excel并运行宏。 Basically my python script is sitting in
基本上我的python脚本位于
C:\Users\adrlee\Desktop\Python files\Automation
and my excel VBA file (Automation.xlsb) is sitting in 而我的Excel VBA文件(Automation.xlsb)位于
C:\Users\adrlee\Desktop\Python files\Automation\Powerpoint
I am running this code 我正在运行这段代码
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");
but i am getting error 但我遇到错误
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)
What am i doing wrong 我究竟做错了什么
Thanks for the comments and hints guys! 谢谢大家的评论和提示! I managed to finally get it right:
我终于做到了:
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");
If fileDir
contains 如果
fileDir
包含
C:\Users\adrlee\Desktop\Python files\Automation\
then joining ..\\Powerpoint\\Automation.xlsb
to it will give 然后加入
..\\Powerpoint\\Automation.xlsb
将得到
C:\Users\adrlee\Desktop\Python files\Automation\..\Powerpoint\Automation.xlsb
which is equivalent to 相当于
C:\Users\adrlee\Desktop\Python files\Powerpoint\Automation.xlsb
because ..
is equivalent to the parent directory, and the parent directory of ...\\Python files\\Automation
is ...\\Python files
. 因为
..
等效于父目录,而...\\Python files\\Automation
的父目录是...\\Python files
。
Your question states that the Excel file is actually 您的问题指出Excel文件实际上是
C:\Users\adrlee\Desktop\Python files\Automation\Powerpoint\Automation.xlsb
so you should really be joining .\\Powerpoint\\Automation.xlsb
to the fileDir
variable. 因此,您实际上应该将
.\\Powerpoint\\Automation.xlsb
加入到fileDir
变量中。 (While ..
refers to the parent directory, .
refers to the existing directory.) (虽然
..
指代父目录, .
指代现有目录。)
ie use: 即使用:
filename = os.path.join(fileDir, './Powerpoint/Automation.xlsb')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.