Export Excel csv django

mail@pastecode.io avatar
unknown
python
2 years ago
1.6 kB
1
Indexable
Never
#openpyxl necessary
import openpyxl, csv 
#Excel download
def ssbs_download_excel(request):
    # Retrieve the query results
    results = Ssb.objects.all()

    # Create the Excel workbook and worksheet
    workbook = openpyxl.Workbook()
    worksheet = workbook.active

    # Add the column headings to the worksheet
    worksheet.append(['Name', 'Lat', 'Long'])

    # Add the data to the worksheet
    for result in results:
        worksheet.append([result.name, result.lat, result.long])

    # Set the filename and content type
    filename = 'listessb.xlsx'
    content_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

    # Create the HttpResponse object
    response = HttpResponse(content_type=content_type)
    response['Content-Disposition'] = f'attachment; filename={filename}'

    # Write the workbook to the response
    workbook.save(response)
    return response

#CSV download
def ssbs_download_csv(request):
    # Retrieve the query results
    results = Ssb.objects.all()

    # Create the HttpResponse object
    response = HttpResponse(content_type='text/csv')
    filename='SSB_' + str(datetime.now().year) + '-' + str(datetime.now().month) + '-' + str(datetime.now().day)
    response['Content-Disposition'] = f'attachment; filename={filename}.csv'

    # Create the CSV writer
    writer = csv.writer(response)

    # Write the column headings to the CSV
    writer.writerow(['Name', 'Lat', 'Long'])

    # Write the data to the CSV
    for result in results:
        writer.writerow([result.name, result.lat, result.long])

    return response