Search code examples
pythonexcelopenpyxlpeewee

How to export data from Python database to Excel


I am building WebApp with Pyhton Flask and peewee. I need to export data from the database and import it to Excel.

I found the openpyxl is python library for working with\n Excel spreadsheets. This is my code:

models.py

class Info(Model):
    ime_prezime=CharField()
    ulica=CharField()
    broj=CharField()

    class Meta():
        database=DATABASE
import openpyxl
import models


wb=openpyxl.load_workbook("ispratnica.xlsx")
type(wb)
sheet = wb["Ispratnica"]
sheet["J2"].value="swongnwrb"
wb.save('{}.xlsx'.format(models.Info.ime_prezime))

When i change wb.save('{}.xlsx'.format(models.Info.ime_prezime)) to ```wb.save('ispratnica1.xlsx'.) the code works perfectly, but when I try use data from the database it gives me error:

OSError: [Errno 22] Invalid argument: '<CharField: Info.ime_prezime>.xlsx' Can someone help me with this one? Please pardon me if I have any mistakes asking this question.


Solution

  • Just read the data out and write it to a csv.

    You need to actually query your model in order to have anything to write out.

    import csv
    
    with open('sheet.csv', 'w') as fh:
        writer = csv.writer(fh)
        for row in Info.select().tuples():
            writer.writerow(row)