django-import-export的匯出
阿新 • • 發佈:2019-01-31
開發環境: windows + python3.6 + django1.11
1.在專案中安裝django-import-export:
pip install django-import-export
2.在settings 的INSTALLED_APPS中新增 django-import-export:
INSTALLED_APPS = [
...
# primarykey 是建立的app
'primarykey',
'import_export',
...
]
3.models.py的模型:
from django.db import models
class Company(models.Model):
# 公司編號
CRNO = models.CharField(max_length=20, primary_key=True)
name = models.CharField(max_length=20, blank=True, null=True)
class Meta:
verbose_name_plural = '公司資訊'
def __str__(self):
return self.name
class Employee(models.Model) :
# 員工號
employee_id = models.CharField(max_length=10, unique=True)
name = models.CharField(max_length=10, blank=True, null=True)
company = models.ForeignKey(Company, blank=True, null=True)
class Meta:
verbose_name_plural = '員工資訊'
def __str__(self):
return self.name
4.定製Resource:
from . import models
from import_export import resources
class Employee_Resource(resources.ModelResource):
def get_export_headers(self):
# 是你想要的匯出頭部標題headers
return ['員工號', '員工姓名', '公司名稱']
class Meta:
model = models.Employee
fields = ('employee_id', 'name', 'company__name',)
export_order = ('employee_id', 'name', 'company__name',)
5.匯出的邏輯:
#在urls.py中
# primarykey 是建立的app
from primarykey import views
url(r'^export/function/(.+)/$', views.export_function, name='匯出'),
#在views.py中
def export_function(request, name):
HEADERS = []
# name 是路由url中的引數
resource_name = '%s_Resource()' % name
export_resource = eval(resource_name)
HEADERS = export_resource.get_export_headers()
dataset = export_resource.export()
book = xlwt.Workbook()
sheet = book.add_sheet('Sheet1') # 建立一個sheet
# -----樣式設定----------------
alignment = xlwt.Alignment() # 建立居中
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
# 頭部樣式
header = xlwt.XFStyle()
header.alignment = alignment
header.font.height = 200
header.font.name = '宋體'
header.font.bold = True # 加粗
# 內容樣式
style = xlwt.XFStyle() # 建立樣式
style.alignment = alignment # 給樣式新增文字居中屬性
style.font.height = 200 # 設定200字型大小(預設10號)
style.font.name = '宋體' # 設定 宋體
style.font.colour_index = 0x77 # 顏色
# 頭部標題 設定樣式
for tag in range(0, len(HEADERS)):
sheet.write(0, tag, HEADERS[tag], header)
# ----------設定列寬--------------
col = sheet.col(tag)
if 520 * (len(HEADERS[tag]) + 2) > 65536:
col.width = 65000
else:
col.width = 520 * (len(HEADERS[tag]) + 2)
# 內容樣式
if dataset:
for line in range(0, len(dataset)):
for col in range(0, len(HEADERS)):
sheet.write(line + 1, col, dataset[line][col], style)
length = len(HEADERS[col])
for row in range(0, len(dataset)):
if len(str(dataset[row][col])) >= len(str(dataset[row - 1][col])) and len(
str(dataset[row][col])) > length:
length = len(str(dataset[row][col]))
# 設定列寬
colwidth = sheet.col(col)
if 520 * (length + 2) > 65536:
colwidth.width = 65000
else:
colwidth.width = 520 * (length + 2)
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=%s.xls' % urlquote(name)
book.save(response)
return response
# 在html中,name就是Employee(你要匯出的model的名稱,定製的Employee_Resource的前半部分,主要是根據自己的命名規則)
<a href="{% url '匯出' name %}" title="匯出" class="btn btn-light"><i class="fa fa-download"></i><span>匯出</span></a>
以上就是匯出的基本邏輯,歡迎各位評論!
在此感謝胡玉新胡老師的幫助!