Python Forum
How to import data from database to excel
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to import data from database to excel
#1
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'>
Reply
#2
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Smile Set 'Time' format cell when writing data to excel and not 'custom' limors 3 496 Mar-29-2021, 09:36 PM
Last Post: Larz60+
  Extract data from PDF page to Excel nathan_nz 1 406 Oct-29-2020, 08:04 PM
Last Post: Larz60+
  I try to import data from Excel table to Word Template. NewbiePyPy 0 557 Oct-21-2020, 12:25 PM
Last Post: NewbiePyPy
  Looping to read data in database CEC68 1 465 Sep-24-2020, 08:54 PM
Last Post: scidam
  Get database used data space from pyodbc susja 1 496 Aug-14-2020, 02:01 PM
Last Post: susja
  sqlite3 database does not save data across restarting the program SheeppOSU 1 745 Jul-24-2020, 05:53 AM
Last Post: SheeppOSU
  Import CSV data into array and turn into integers DoctorSmiles 5 860 Jul-16-2020, 10:47 AM
Last Post: perfringo
  data frame excel cell calulation buunaanaa 1 727 Jul-04-2020, 06:00 PM
Last Post: buunaanaa
  Importing data from a text file into an SQLite database with Python macieju1974 7 1,033 Jun-29-2020, 08:51 PM
Last Post: buran
  Exporting data from python into excel Zankawah 5 940 Jun-02-2020, 03:17 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020