python读取mdb文件数据,并保存为excel

问题: 有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}')
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容