1

I am using pyodbc to access an access (accdb) file. I want to add an excel workbook into the access database programatically, but cannot find an API to do so. Here is my current code:

import pyodbc
DBFile = r'C:\Documents and Settings\IA.accdb'
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBFile)

exFile = r'C:\Documents and Settings\IA_2006.xls'
conn1 = pyodbc.connect('DRIVER={Microsoft Excel Driver \ 
                       (*.xls)};DBQ='+exFile,autocommit=True)

cursor = conn.cursor()
####IA_1 is a table within IA.accdb
cursor.execute('select * from IA_1')
row = cursor.fetchone()
####For debugging, print a line
if row:
        print row

How should I import the data from the excel file (IA_2006.xls) into the IA.accdb?

1 Answer 1

3

It seems like you got to a certain point and gave up.
Don't give up! :-)

You've made the connection to the Excel spreadsheet, now you need to read it*.

curs1 = conn1.cursor()
# the following returns list of tuples
excel_results = curs1.execute('select [a_column]
                               from [Sheet1$]').fetchall()

Then you can insert to your MS Access db, e.g.:

curs.executemany('insert into mytable (mycolumn) values (?)', excel_results)
conn.commit()

*If in doubt, Excel sheet names can be found by running the following:

for row in curs1.tables():
    print row.table_name
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.