Python Forum
How to import data from database to excel - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to import data from database to excel (/thread-19136.html)



How to import data from database to excel - nick123 - Jun-14-2019

I am using microsoft access database.
I want to copy data from the table with column names and paste it into a excel file.
I try to copy but I got some errors

import openpyxl as op
import pyodbc

con = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=path;')
cr = con.cursor()



loc = (r'path of the excel file')

wb = op.load_workbook(loc)
sheet = wb.create_sheet(0)
sheet.title="Trial"

cr.execute('select * from  detail')
result=list(cr.fetchall())

sheet.append(cr.column_name)

for row in cr.columns(table='detail'):
    sheet.append(row.column_name)

for row in result:
    sheet.append(row)
Error:
Traceback (most recent call last): File "C:/Users/Nick/PycharmProjects/py/venv/excel.py", line 21, in <module> sheet.append(rows.column_name) File "C:\Users\Nick\PycharmProjects\py\venv\lib\site-packages\openpyxl\worksheet\worksheet.py", line 661, in append self._invalid_row(iterable) File "C:\Users\Nick\PycharmProjects\py\venv\lib\site-packages\openpyxl\worksheet\worksheet.py", line 792, in _invalid_row type(iterable)) TypeError: Value must be a list, tuple, range or generator, or a dict. Supplied value is <class 'str'>



RE: How to import data from database to excel - sm51251 - Oct-09-2019

for row in result:
sheet.append(row)

In that, you need to make a row as List as follows:
for row in result:
listrow = list(row)
sheet.append(listrow)