Django:将对象从数据库导出到excel
我的模板中有以下内容:Django:将对象从数据库导出到excel,django,excel,Django,Excel,我的模板中有以下内容: <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&g
<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>
下面是url.py中的mu url:
url(r'^export$', 'export_excel', name='export_excel'),
它导出名为books.xls的文件中的书籍,这里的问题是它将它们导出为第一个方框(A1)中的“书籍对象”
如果我想将每个“book_属性”放在单独的方框中,将每个“book”放在单独的行中,我该怎么办?我认为问题在于,只需将book对象的列表传递给导出文件即可
books = Book.objects.all()
此行只返回一个对象列表
我认为您可能需要迭代Book对象的每个属性。
用显示所有字段的元组替换每个Book对象。
困难的方法是做类似的事情
books\u list=map(lambda x:(x.book\u id,x.book\u name,…图书的所有字段),books)
您将图书列表传递给导出文件而不是图书。您正在发送一个名为“books.xls”的文件,并正确地表示它是Excel电子表格。。。但事实并非如此。您完全错过了实际创建包含数据的Excel电子表格的步骤(这可能是此处工作的80%)
尝试在web上搜索如何使用Python创建excel电子表格。使用tablib的工作示例,这是一个优秀的表格数据集库。
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"'
writer = csv.writer(response)
writer.writerow(['Book', 'Author'])
for book in books:
writer.writerow([book.book_name, book.author])
return response
from django.http import HttpResponse
import tablib
headers = ('Book', 'Author')
data = []
data = tablib.Dataset(*data, headers=headers)
books = Book.objects.all()
for book in books:
data.append((book.book_name, book.author))
response = HttpResponse(data.xls, content_type='application/vnd.ms-excel;charset=utf-8')
response['Content-Disposition'] = "attachment; filename=export.xls"
return response
使用我的插件的解决方案:
from django.http import HttpResponse
import tablib
headers = ('Book', 'Author')
data = []
data = tablib.Dataset(*data, headers=headers)
books = Book.objects.all()
for book in books:
data.append((book.book_name, book.author))
response = HttpResponse(data.xls, content_type='application/vnd.ms-excel;charset=utf-8')
response['Content-Disposition'] = "attachment; filename=export.xls"
return response
import djang_excel as excel
import pyexcel.ext.xls # in order to handle 'xls' format
# import pyexcel.ext.xlsx # in order to handle 'xlsx' format
# import pyexcel.ext.ods # in order to handle 'ods' format
def export_excel(self, request):
# Book as django model, 'xls' as file format
response = excel.make_response_from_a_table(Book, 'xls')
response['Content-Disposition'] = 'attachment; filename="books.xls"'
return response