Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
download csv excel response   0   54023
How to download data as CSV and Excel file in Django

Sometimes we are required to dump database data in CSV or Excel file. In this article we will see how to download the data in CSV or Excel file in Django.



Download data as Excel file in Django:

For downloading data in excel file we need to add xlwt package in our environment. I assume you are using virtual environment to develop your django app.

It is always recommended to user virtual environment. Once virtual environment is activated, Run this command to add xlwt  package.

pip install xlwt


Inside your view, import xlwt package. Use below code in your view in views.py  file to create and download excel file.

import xlwt
from django.http import HttpResponse


def download_excel_data(request):
	# content-type of response
	response = HttpResponse(content_type='application/ms-excel')

	#decide file name
	response['Content-Disposition'] = 'attachment; filename="ThePythonDjango.xls"'

	#creating workbook
	wb = xlwt.Workbook(encoding='utf-8')

	#adding sheet
	ws = wb.add_sheet("sheet1")

	# Sheet header, first row
	row_num = 0

	font_style = xlwt.XFStyle()
	# headers are bold
	font_style.font.bold = True

	#column header names, you can use your own headers here
	columns = ['Column 1', 'Column 2', 'Column 3', 'Column 4', ]

	#write column headers in sheet
	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()

	#get your data, from database or from a text file...
	data = get_data() #dummy method to fetch data.
	for my_row in data:
		row_num = row_num + 1
		ws.write(row_num, 0, my_row.name, font_style)
		ws.write(row_num, 1, my_row.start_date_time, font_style)
		ws.write(row_num, 2, my_row.end_date_time, font_style)
		ws.write(row_num, 3, my_row.notes, font_style)

	wb.save(response)
	return response
 


Download data as CSV file in Django:

Import csv and smart_str package in your view. Use below code to download the data in CSV format.

import csv
from django.utils.encoding import smart_str


def download_csv_data(request):
	# response content type
	response = HttpResponse(content_type='text/csv')
	#decide the file name
	response['Content-Disposition'] = 'attachment; filename="ThePythonDjango.csv"'

	writer = csv.writer(response, csv.excel)
	response.write(u'\ufeff'.encode('utf8'))

	#write the headers
	writer.writerow([
		smart_str(u"Event Name"),
		smart_str(u"Start Date"),
		smart_str(u"End Date"),
		smart_str(u"Notes"),
	])
	#get data from database or from text file....
	events = event_services.get_events_by_year(year) #dummy function to fetch data
	for event in events:
		writer.writerow([
			smart_str(event.name),
			smart_str(event.start_date_time),
			smart_str(event.end_date_time),
			smart_str(event.notes),
		])
	return response
 

Let us know by commenting if you are facing any issue.


Host your Django App on PythonAnyWhere for Free.


download csv excel response   0   54023
0 comments on 'How To Download Data As Csv And Excel File In Django'
Login to comment


Related Articles:
Python Requests Library: Sending HTTP GET and POST requests using Python
Python requests library to send GET and POST requests, Sending query params in Python Requests GET method, Sending JSON object using python requests POST method, checking response headers and response status in python requests library...
How to display PDF in browser in Django instead of downloading it
display pdf in browser in Django, PDF response in Django, How to display PDF response in Django, Generating PDF from HTML template in Django, Download PDF in Django, Inline pdf display in Django, In browser PDF display in Django, Showing employee payslip in the browser using Django...
Generating and Returning PDF as response in Django
Creating PDF documents in Python and Django, Returning PDF as response in Django, Generating PDF from HTML template in Django, Using pdfkit and wkhtmltopdf in python and django...
How to upload and process the Excel file in Django
How to upload and process the content of excel file in django without storing the file on server. Process Excel file content in Django. Uploading and reading Excel file content in Django 2.0 without storing it on server....
DigitalOcean Referral Badge

© 2024-2025 Python Circle   Contact   Sponsor   Archive   Sitemap