csv文件是逗號分隔值(Comma-Separated Values,CSV),有時也稱分隔值,因為分割字符也可不是逗號,其文件以純文本形式存儲表格數據(數字和文件)。
注:可被常見制表工具,如excel等直接進行讀取。
python提供了內建庫-csv,可直接通過該庫操作csv文件
例:
import csv
with open(‘xx.csv’, ‘w’, newline=’’) as csvfile:
writer = csv.writer(csvfile)
writer.writerow([‘a’, ‘b’, ‘c’])
在網站中,實現下載csv,注意如下:
響應Content-Type類型需修改為text/csv。這告訴浏覽器該文檔是csv文件,而不是html文件。
響應會獲得一個額外的Content-Disposition標頭,其中包含csv文件的名稱。它將被浏覽器用於開啟“另存為…”對話框。
例:
(a)views.py
def test_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;filename="test.csv"'
all_data = ['a', 'b', 'c', 'd']
writer = csv.writer(response)
writer.writerow(all_data)
return response
(b)urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('test_csv', views.test_csv),
]
例:生成分頁數據中的csv文件
(a)views.py
def make_page_csv(request):
page_num = request.GET.get('page', 1)
all_data = ['a', 'b', 'c', 'd', 'e']
# 初始化paginator
paginator = Paginator(all_data, 2)
# 初始化 具體頁碼的page對象
c_page = paginator.page(int(page_num))
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;filename="page-%s.csv"'%(page_num)
writer = csv.writer(response)
for b in c_page:
writer.writerow([b])
return response
(b)urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('test_page', views.test_page),
path('make_page_csv', views.make_page_csv),
]
(c)template/test_page.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分頁</title>
</head>
<body>
<a href="/make_page_csv?page={
{ c_page.number }}">生成csv</a>
{% for p in c_page %}
<p>{
{ p }}</p>
{% endfor %}
{% if c_page.has_previous %}
<a href="/test_page?page={
{ c_page.previous_page_number }}">上一頁</a>
{% else %}
上一頁
{% endif %}
{% for p_num in paginator.page_range %}
{% if p_num == c_page.number %}
{
{ p_num }}
{% else %}
<a href="/test_page?page={
{ p_num }}">{
{ p_num }}</a>
{% endif %}
{% endfor %}
{% if c_page.has_next %}
<a href="/test_page?page={
{ c_page.next_page_number }}">下一頁</a>
{% else %}
下一頁
{% endif %}
</body>
</html>