4

I need help with exporting data using a template. I installed django-import-export and added it to admin panel, now I can only export data from the admin panel. I want to know how can i export excel file using template.

3
  • What have you tried or looked at so far? Commented Sep 13, 2019 at 13:53
  • i tried this code def export_page(request): dataset = AddResource().export() print (dataset.csv) return render (request ,'export_page.html', ) Commented Sep 13, 2019 at 14:10
  • Some one please help ;( Commented Sep 13, 2019 at 14:12

4 Answers 4

9

This should get you started:

import StringIO
import xlsxwriter
from django.http import HttpResponse

def export_page(request):
    # create our spreadsheet.  I will create it in memory with a StringIO
    output = StringIO.StringIO()
    workbook = xlsxwriter.Workbook(output)
    worksheet = workbook.add_worksheet()
    worksheet.write('A1', 'Some Data')
    workbook.close()

    # create a response
    response = HttpResponse(content_type='application/vnd.ms-excel')

    # tell the browser what the file is named
    response['Content-Disposition'] = 'attachment;filename="some_file_name.xlsx"'

    # put the spreadsheet data into the response
    response.write(output.getvalue())

    # return the response
    return response
Sign up to request clarification or add additional context in comments.

3 Comments

For Python 3 , from io import StringIO
this most recent comment is pretty important @chris-curvey could you update your answer?
7

I tried the same with newer version of Django and after trial and error found this worked.

import io
import xlsxwriter

def excelreport(request):

  buffer = io.BytesIO()
  workbook = xlsxwriter.Workbook(buffer)
  worksheet = workbook.add_worksheet()
  worksheet.write('A1', 'Some Data')
  workbook.close()
  buffer.seek(0)

  return FileResponse(buffer, as_attachment=True, filename='report.xlsx')

2 Comments

Hello, my code executes but I dont get any file in return...what should i do?
can you explain the purpose of buffer.seek(0) it worked on Django 4.1.7
2

You can alos use xlwt if you really need to export to a .xls file. You will be able to add formating as bold font, font size, define column size, etc.

$ pip install xlwt

import xlwt

from django.http import HttpResponse
from django.contrib.auth.models import User

def export_users_xls(request):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="users.xls"'

    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Users')

    # Sheet header, first row
    row_num = 0

    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns = ['Username', 'First name', 'Last name', 'Email address', ]

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    # Sheet body, remaining rows
    font_style = xlwt.XFStyle()

    rows = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
    for row in rows:
        row_num += 1
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)

    wb.save(response)
    return response

Comments

1

If you are using pandas, this is probably the easiest and most concise way:

import pandas as pd
from django.http import HttpResponse


def export_excel_file(request):
    df = pd.read_excel("excel_filename.xlsx")

    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = f'attachment; filename=excel_filename.xlsx'
    df.to_excel(response, index=False)
    
    return response

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.