【发布时间】:2021-01-07 23:52:42
【问题描述】:
使用 pyodbc,我正在尝试遍历 Excel 中的工作表,读取以字符串“Appointment”开头的工作表,然后将结果写入 Access DB 中的现有表中。
我能够遍历所有工作表并确定以“约会”开头的工作表(其中有四个 - Appointment1、Appointment2 等)。 我还可以读取找到的任何一张表上的数据,并将结果写入数据库表。 当我尝试在 for 循环中执行所有这些操作时,我能够获取所有工作表名称,但是一旦我执行()一个 select 语句,循环就会停止。
它不会出错 - print() 语句有效,但循环在第二个 print 语句后停止。如果我将第二个 print() 注释掉,第一个 print 将返回四个结果。
Cursor.commit() 不会改变行为。
# execute select stmt
def select_xls_data(tbl_name):
select_stmt_XLS = 'SELECT * from [' + tbl_name + ']'
result_XLS = crsr_XLS.execute(select_stmt_XLS).fetchall()
return result_XLS
# loop through XLS sheets
for table_info in crsr_XLS.tables():
tbl_name = table_info.table_name
if (tbl_name.startswith('Appointment')):
print(tbl_name) # will succesfully loop through all sheets
print(select_xls_data(tbl_name)) # will only loop once
【问题讨论】:
标签: python excel ms-access pyodbc