Python:将excel文件添加到access数据库

发布于 2024-10-01 01:56:37 字数 669 浏览 4 评论 0原文

我正在使用 pyodbc 访问访问(accdb)文件。我想以编程方式将 Excel 工作簿添加到 Access 数据库中,但找不到执行此操作的 API。这是我当前的代码:

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

如何将 Excel 文件(IA_2006.xls)中的数据导入到 IA.accdb 中?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十年九夏 2024-10-08 01:56:37

看来你到了一定程度就放弃了。
不要放弃! :-)

您已连接到 Excel 电子表格,现在您需要阅读它*。

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

然后您可以插入到您的 MS Access 数据库中,例如:

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

*如果有疑问,可以通过运行以下命令找到 Excel 工作表名称:

for row in curs1.tables():
    print row.table_name

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文