问题: 有mdb文件,但本地没有access无法打开,就用python 将它转为excel;
环境及相关的包:pyodbc, openpyxl
代码:
import pyodbc
import pandas as pd
# MDB 文件路径
mdb_path = r'D:\test.mdb'
# 连接字符串
connection_string = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + mdb_path
# 创建数据库连接
connection = pyodbc.connect(connection_string)
# 获取所有表的信息
cursor = connection.cursor()
tables = cursor.tables(tableType='TABLE')
# 打印表名
for table in tables:
print(table.table_name)
# 查询数据
query = 'SELECT * FROM table'
data_frame = pd.read_sql(query, connection)
print(data_frame)
# 关闭数据库连接
connection.close()
# 指定输出excel文件路径
excel_path = r'D:\a.xlsx'
# 将Dataframe 写入excel文件
data_frame.to_excel(excel_path, index=False)
print(f'数据已成功保存到 {excel_path}')