我的代碼是Excel中訪問pywin32
#Opens template for creating final report
excel = win32.dynamic.Dispatch('Excel.Application')
template = os.path.abspath((folderpath+'\Poop.xlsx'))
wb = excel.Workbooks.Open(template)
freshws= wb.Sheets("Fresh") #Sheet names must match perfectly
secws= wb.Sheets("sec")
cur.execute("Select * from FIRALL")
freshdata=list(cur.fetchall())
#writes to the first sheet
datarowlen=0
for i,a in enumerate(freshdata):
datarowlen = len(a)
for j,b in enumerate(a):
freshws.Cells(i+1,j+1).Value = a[j]
cur.execute("Select * from SECVE")
secdata=list(cur.fetchall())
#writes to the second sheet
datarowlen=0
for i,a in enumerate(secdata):
datarowlen = len(a)
for j,b in enumerate(a):
secws.Cells(i+1,j+1).Value = a[j]
#saves the report
wb.SaveAs()
wb.Close()
的錯誤,當我跑我的代碼是
Traceback (most recent call last):
File "main.py", line 369, in <module>
wb = excel.Workbooks.Open(template)
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel'
, "Microsoft Excel cannot access the file 'path to stuff------------------------
Poop Report\\Poop.xlsx'. There are several possible reasons:\n\n\u2022 The file
name or path does not exist.\n\u2022 The file is being used by another program.\
n\u2022 The workbook you are trying to save has the same name as a currently ope
n workbook.", 'xlmain11.chm', 0, -2146827284), None)
我得到一個彈出對話框說訪問被拒絕,我得到。該文件不是隻讀文件,而是我試圖打開的工作簿的所有者。我試過
win32.gencache.EnsureDispatch('Excel.Application')
我仍然得到相同的錯誤。有什麼我失蹤?我轉而採用動態思維,後期綁定可以解決這個錯誤。
我的另一個錯誤是Pywins -2147418111錯誤,當我試圖修復此代碼。
你的'folderpath'變量來自哪裏?因爲它看起來像是通過Excel路徑的東西------------------------ Poop Report \\ Poop.xlsx'' ,這顯然不是一個有效的途徑,而這正是你得到這個錯誤的原因。 – abarnert
我只是把它放在那裏隱藏通路,通路不是問題,因爲我已經使用openpyxt沒有問題,但它無法處理數據透視表或更新它們。 –