我正在尝试使用Python comtypes库在excel电子表格中创建一个QueryTable,但是得到一个相当无意义的错误......
在vba中(在工作簿中的模块中),以下代码可以正常工作:
Sub CreateQuery() Dim con As ADODB.Connection Dim rs As ADODB.Recordset Dim ws As Worksheet Dim qt As QueryTable Set ws = ActiveWorkbook.Sheets(1) Set con = New ADODB.Connection con.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\to\Db.mdb;") Set rs = New ADODB.Recordset rs.Open "Select * from [tbl Base Data];", con Set qt = ws.QueryTables.Add(rs, ws.Range("A1")) qt.Refresh End Sub
但是以下Python代码:
import sys import comtypes.client as client def create_querytable(): constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Path\\to\\Db.mdb" conn = client.CreateObject("ADODB.Connection", dynamic = True) rs = client.CreateObject("ADODB.Recordset", dynamic = True) SQL = "Select * from [tbl Base Data];" conn.Open(constring) rs.Open(SQL, conn) excel = client.CreateObject("Excel.Application", dynamic = True) excel.Visible = True ws = excel.Workbooks.Add().Sheets(1) qt = ws.QueryTables.Add(rs, ws.Range["A1"]) qt.Refresh() rs.Close() conn.Close()
抛出无用的错误消息:
Traceback (most recent call last): File "", line 1, in create_querytable() File "C:/Documents and Settings/cvmne250/Desktop/temp.py", line 17, in create_querytable qt = ws.QueryTables.Add(rs, ws.Range["A1"]) File "G:\ISA\SPSS\comtypes\lib\comtypes\client\lazybind.py", line 160, in caller File "G:\ISA\SPSS\comtypes\lib\comtypes\automation.py", line 628, in _invoke COMError: (-2147352567, 'Exception occurred.', (None, None, None, 0, None))
关于这里发生了什么的任何想法?
谢谢!