generate Excel files from DB response. Flask REST API

Viewed 18

I'm trying to generate excel/CSV files as a response generated at runtime. I tried using flask-excel but not getting the expected results. For example: if the data in DB is,

| name | age | sex   |
| ---- | --- | ----- |
| Ram  | 25  | male  |
| Sita | 24  | female|

the output excel should look similar to this.

2 Answers

Flask Excel does the job, but the installation steps are slightly different from what's mentioned on the documentation

  1. import flask_excel
  2. init
  3. Use flask_excel.make_response_from_array or other relevant functions.

This should work

You can also opt for the csv module that comes with python. try something like this

This is how I do it in Django. Hope it will be useful

import csv
from django.http import HttpResponse

def generate_csv_file():
    response = HttpResponse(
        content_type='text/csv',
         )
    response['Content-Disposition'] = 'attachment; filename=' + 
    f"custom_filename" + '.csv'

    writer = csv.writer(response)
    writer.writerow(['Name','Age' ,'Sex'])
    
    '''
    db_row is a query set from your database in this context
    '''

    for item in db_row:
        writer.writerow([f'{item.name}', f'{item.age}', f'{item.sex}'])
    return reponse

generate_csv_file()

Please use equivalent flask code for the HttpResponse code.

Related