how to import an excel file and save it as cab in python

To import an excel file and save it as a compressed access database (cab file) in Python, we can use the following code:

main.py
import pandas as pd
import pyodbc

# Import the Excel file
df = pd.read_excel('data.xlsx')

# Connect to the Access database using pyodbc
conn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=path/to/database.accdb')
cur = conn.cursor()

# Save the dataframe to Access database table
table_name = 'table1'
df.to_sql(table_name, conn, index=False, if_exists='replace')

# Compress the Access database file into a cab file
cab_file = 'output.cab'
cur.execute(f'SELECT APPENDFILE(\'{cab_file}\')')
cur.commit()

# Clean up
cur.close()
conn.close()
568 chars
23 lines

This code uses the pandas library to import the Excel file as a dataframe. We then use the pyodbc library to connect to an Access database and save the dataframe as a table. Finally, we compress the Access database file into a cab file using a special SQL command (APPENDFILE).

gistlibby LogSnag