問題: 有mdb文件,但本地沒有access無法打開碟渺,就用python 將它轉(zhuǎn)為excel;
環(huán)境及相關(guān)的包: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
# 創(chuàng)建數(shù)據(jù)庫連接
connection = pyodbc.connect(connection_string)
# 獲取所有表的信息
cursor = connection.cursor()
tables = cursor.tables(tableType='TABLE')
# 打印表名
for table in tables:
print(table.table_name)
# 查詢數(shù)據(jù)
query = 'SELECT * FROM table'
data_frame = pd.read_sql(query, connection)
print(data_frame)
# 關(guān)閉數(shù)據(jù)庫連接
connection.close()
# 指定輸出excel文件路徑
excel_path = r'D:\a.xlsx'
# 將Dataframe 寫入excel文件
data_frame.to_excel(excel_path, index=False)
print(f'數(shù)據(jù)已成功保存到 {excel_path}')