how to tips   0   3
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 tips   0   3

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: