Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: export object from database to excel

Tags:

excel

django

i have this in my template :

<table>
<tr><td>book_id</td><td>book name</td><td>book_author</td></tr>
{% for book in books %}
<tr><td>{{ book.book_id }}</td><td>{{ book.book_name }}</td><td>{{ book.book_author }}</td></tr>
{% endfor %}
</table>
<a href="/export">Export to Excel !</a>

my view seems to be like this:

def export_excel(request):
    books = Book.objects.all()
    response = HttpResponse(books , content_type='application/vnd.ms-excel;charset=utf-8')
    response['Content-Disposition'] = 'attachment; filename="books.xls"'
    return response

And here is mu url in urls.py:

url(r'^export$', 'export_excel', name='export_excel'),

It export books in file that named books.xls and the probleme here is that it export them as "Book objects" in the first square (A1)

what should i do if i want to make every "book_attribute" in separate square and every "book" in separate line ?

like image 966
Drwhite Avatar asked Jun 19 '26 15:06

Drwhite


1 Answers

You're sending something called "books.xls", and correctly signalling that it's an Excel spreadsheet... but it isn't. You've completely missed the step of actually creating an Excel spreadsheet containing your data (which is probably 80% of the work here).

Try searching the web for how to create an excel spreadsheet in Python.

like image 168
user9876 Avatar answered Jun 21 '26 06:06

user9876



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!