美文网首页
python读取mdb文件数据,并保存为excel

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

作者: 丙吉 | 来源:发表于2024-09-02 15:46 被阅读0次
    问题: 有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}')
    

    相关文章

      网友评论

          本文标题:python读取mdb文件数据,并保存为excel

          本文链接:https://www.haomeiwen.com/subject/dkihljtx.html