Generating CSV, Excel files Using Python

from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
import csv
from django.http import HttpResponse
from app_name.models import Book
def generate_book_csv(request):
books = Book.objects.all()
# Create the HttpResponse object with CSV header.This tells browsers that
# the document is a CSV file.
response = HttpResponse(content_type='text/csv')
# The response also has additional Content-Disposition header, which contains
# the name of the CSV file.
response['Content-Disposition'] = 'attachment; filename=books.csv'
# The csv.writer function takes file-like object as argument i.e.,HttpResponse object
writer = csv.writer(response)
# For each row in your CSV file, call writer.writerow function by passing
# a list or tuple to it.
writer.writerow(['ID', 'Title', 'Description'])
for book in books:
writer.writerow([book.id, book.title, book.description])
return response
import xlwt
from django.http import HttpResponse
from app_name.models import Book
def generate_book_excel(request):
books = Book.objects.all()
# Create the HttpResponse object with Excel header.This tells browsers that
# the document is a Excel file.
response = HttpResponse(content_type='application/ms-excel')
# The response also has additional Content-Disposition header, which contains
# the name of the Excel file.
response['Content-Disposition'] = 'attachment; filename=books.xls'
# Create object for the Workbook which is under xlwt library.
workbook = xlwt.Workbook()
# By using Workbook object, add the sheet with the name of your choice.
worksheet = workbook.add_sheet("Books")

row_num = 0
columns = ['ID', 'Title', 'Description']
for col_num in range(len(columns)):
# For each cell in your Excel Sheet, call write function by passing row number,
# column number and cell data.
worksheet.write(row_num, col_num, columns[col_num])

for book in books:
row_num += 1
row = [book.id,book.title,book.description]
for col_num in range(len(row)):
worksheet.write(row_num, col_num, row[col_num])

workbook.save(response)
return response

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store