how-to download csv excel   0   1451
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.


how-to download csv excel   0   1451

Related Articles:
Python Script 3: Validate, format and Beautify JSON string Using Python
Validating json using python code, format and beautify json file using python, validate json file using python, how to validate, format and beautify json...
Encryption-Decryption in Python Django
How to encrypt and decrypt the content in DJango. Encrypting the critical information in Django App. Encrypting username, email and password in Django...
Adding Robots.txt file to Django Application
Adding robots.txt file in your Django application. Easiest way to add robots.txt file. Django application robots.txt file. Why should you add robots.txt file in your Django Application....
Scraping 10000 tweets in 60 seconds using celery, RabbitMQ and Docker cluster with rotating proxy
Scrapping large amount of tweets within minutes using celery, RabbitMQ and docker cluster. Scraping huge data quickly using docker cluster with TOR....

0 thoughts on 'How To Download Data As Csv And Excel File In Django'
Leave a comment:


*All Fields are mandatory. **Email Id will not be published publicly.


SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.



Recent Posts:






© pythoncircle.com 2018-2019