[英]Python Export Report Microsoft Access using win32com.client
I have some reports in Access format and I want to generate PDF of these reports from Python script.我有一些 Access 格式的报告,我想从 Python 脚本生成这些报告的 PDF。
I read a lot of questions and answers about how to do it and came up with this simple script.我阅读了很多关于如何做到这一点的问题和答案,并想出了这个简单的脚本。
My code is:我的代码是:
import win32com.client as win
import os
access = win.Dispatch("Access.Application")
db = access.OpenCurrentDatabase(filename)
access.DoCmd.OpenReport(report_name,2)
access.DoCmd.OutputTo(3, report_name, r'PDF Format (*.pdf)','c:/temp/test.pdf' )
access.DoCmd.CloseDatabase
access.Quit()
access=None
Executing the script first time gives this error (translate for me in English):第一次执行脚本会出现此错误(为我翻译成英文):
pywintypes.com_error: (-2147352567, 'An exception occurred.', (0, None, ' Cannot execute this action now.', None, -1, -2146825802), None)
And file Access is open.并且文件访问是打开的。
The second time I execute, it says The database is already open.
我第二次执行时,它说The database is already open.
When I close the Access and execute it gives the first error again.当我关闭 Access 并执行它时,它再次给出了第一个错误。
UPDATE: Now I change my code for closing database while script is executing and is the second time I executed, and then the scripts works fine.更新:现在我在脚本执行时更改了关闭数据库的代码,这是我第二次执行,然后脚本工作正常。
import win32com.client as win
import os
import time
def file_open(file_name):
if os.path.exists(file_name):
try:
os.rename(file_name, file_name) #can't rename an open file so an error will be thrown
return False
except:
print("File Open "+file_name)
time.sleep(2)
file_open(file_name)
return True
else:
return False
raise NameError
access = win.Dispatch("Access.Application")
file_open(filename)
db = access.OpenCurrentDatabase(filename)
access.DoCmd.OpenReport(report_name,2)
if os.path.isfile('c:/temp/test.pdf'):
os.remove('c:/temp/test.pdf')
access.DoCmd.OutputTo(3, report_name, r'PDF Format (*.pdf)','c:/temp/test.pdf' )
access.DoCmd.CloseDatabase
access.Quit()
access=None
After this correct execution, if I executed another time I have the first error.在正确执行之后,如果我再次执行,我会遇到第一个错误。 I execute for second time and then works fine again.我第二次执行,然后再次正常工作。
Finally I find this solution.最后我找到了这个解决方案。 It's not better, but it works.这不是更好,但它有效。 If someone have a better solution please let me now.如果有人有更好的解决方案,请让我现在。
The solution is kill MSACCESS process in windows.解决方法是在 windows 中杀死 MSACCESS 进程。
This is my code:这是我的代码:
import win32com.client as win
import os
access = win.Dispatch("Access.Application")
db = access.OpenCurrentDatabase(filename)
access.DoCmd.OpenReport(report_name,2)
if os.path.isfile('c:/temp/test.pdf'): # Delete previous PDF
os.remove('c:/temp/test.pdf')
access.DoCmd.OutputTo(3, report_name, r'PDF Format (*.pdf)','c:/temp/test.pdf' )
access.DoCmd.CloseDatabase
os.system("taskkill /im MSACCESS.exe") # Kill process in wondows
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.