[英]How to export data in python with excel format?
def export_to_excel(request):
lists = MyModel.objects.all()
# your excel html format
template_name = "sample_excel_format.html"
response = render_to_response(template_name, {'lists': lists})
# this is the output file
filename = "model.csv"
response['Content-Disposition'] = 'attachment; filename='+filename
response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-16'
return response
from django.conf.urls.defaults import *
urlpatterns = patterns('app_name.views',
url(r'^export/$', 'export_to_excel', name='export_to_excel'),
)
<a href="{% url app_name:export_to_excel %}">Export</a>
沒有任何文件選項可供下載,也沒有給出任何錯誤,但我可以在日志中看到所有結果,其工作正常。
我認為導出excel文件的解決方案是:
if 'excel' in request.POST:
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=Report.xlsx'
xlsx_data = WriteToExcel(weather_period, town)
response.write(xlsx_data)
return response
在這個例子中,用於導出的庫是 xlsxWriter。 這是一個非常完整和實用的解決方案,還有許多其他解決方案: http : //assist-software.net/blog/how-export-excel-files-python-django-application 。
這似乎是基於通過更改文件名和 MIME 類型來欺騙 excel 打開 HTML 表格的做法。 為了完成這項工作,HTML 文件必須組裝一個 HTML 表,這很可能會觸發警告,即文件的真實內容與聲明的內容不同。
恕我直言,這是一個粗略的黑客,應該避免。 相反,您可以使用xlwt 模塊創建一個真正的 excel 文件,或者您可以使用csv模塊創建一個真正的 CSV 文件。
[更新]
在查看您引用的博客文章后,我發現它推薦了另一種不好的做法:使用除 csv 模塊以外的任何東西來生成 CSV 文件都是危險的,因為如果數據包含分隔符、引號或換行符,您最終可能會遇到錯誤CSV。 csv 模塊將處理所有極端情況並生成正確格式化的輸出。
我見過有人使用 Django 模板命名文件“something.xls”並使用 HTML 表而不是 CSV 格式,但這也有一些極端情況。
您似乎正在嘗試使用 HTML 內容生成 Excel 工作簿。 我不知道 Excel(或 LibreOffice)是否能夠打開這樣的文件,但我認為這不是正確的方法。
您應該首先生成一個 excel 文件:您可以將csv 、 xlwt用於xls
和openpyxl用於xlsx
文件的內容可以傳遞給HttpResponse
例如,如果您使用 xlwt:
import xlwt
wb = xlwt.Workbook()
#use xlwt to fill the workbook
#
#ws = wb.add_sheet("sheet")
#ws.write(0, 0, "something")
response = HttpResponse(mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=the-file.xls'
wb.save(response)
return response
你也可以看看
django-excel-response為您完成所有工作。 (我認為它不支持 xlsx 格式)
我希望它有幫助
除了其他答案中顯示的選項之外,您還可以使用XlsxWriter創建 Excel 文件。
請參閱此示例。
將數據導出到 XLS 文件
如果您確實需要導出到 .xls 文件,請使用它。 您將能夠添加格式為粗體、字體大小、定義列大小等。
首先,安裝xlwt模塊。 最簡單的方法是使用pip。
pip install xlwt
視圖.py
import xlwt
from django.http import HttpResponse
from django.contrib.auth.models import User
def export_users_xls(request):
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="users.xls"'
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('Users')
# Sheet header, first row
row_num = 0
font_style = xlwt.XFStyle()
font_style.font.bold = True
columns = ['Username', 'First name', 'Last name', 'Email address', ]
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()
rows = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
for row in rows:
row_num += 1
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style)
wb.save(response)
return response
網址.py
import views
urlpatterns = [
...
url(r'^export/xls/$', views.export_users_xls, name='export_users_xls'),
]
模板.html
<a href="{% url 'export_users_xls' %}">Export all users</a>
閱讀其官方文檔,了解有關 xlwt 模塊的更多信息。 https://simpleisbetterthancomplex.com/tutorial/2016/07/29/how-to-export-to-excel.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.