簡體   English   中英

Python 使用 win32com.client 導出報告 Microsoft Access

[英]Python Export Report Microsoft Access using win32com.client

我有一些 Access 格式的報告,我想從 Python 腳本生成這些報告的 PDF。

我閱讀了很多關於如何做到這一點的問題和答案,並想出了這個簡單的腳本。

我的代碼是:

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

第一次執行腳本會出現此錯誤(為我翻譯成英文):

pywintypes.com_error: (-2147352567, 'An exception occurred.', (0, None, ' Cannot execute this action now.', None, -1, -2146825802), None)

並且文件訪問是打開的。

我第二次執行時,它說The database is already open. 當我關閉 Access 並執行它時,它再次給出了第一個錯誤。

更新:現在我在腳本執行時更改了關閉數據庫的代碼,這是我第二次執行,然后腳本工作正常。

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

在正確執行之后,如果我再次執行,我會遇到第一個錯誤。 我第二次執行,然后再次正常工作。

最后我找到了這個解決方案。 這不是更好,但它有效。 如果有人有更好的解決方案,請讓我現在。

解決方法是在 windows 中殺死 MSACCESS 進程。

這是我的代碼:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM