定义一个用于导出的序列化器
class ExportUserProfileSerializer(CustomModelSerializer):
"""
用户导出 序列化器
"""
last_login = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
dept__deptName = serializers.CharField(source='dept.deptName', default='')
dept__owner = serializers.CharField(source='dept.owner', default='')
gender = serializers.CharField(source='get_gender_display',read_only=True)
class Meta:
model = Users
fields = ( 'username', 'name', 'email', 'mobile', 'gender', 'is_active', 'last_login', 'dept__deptName',
'dept__owner')
1.export_field_label 是Excel表的表头,为一个list字段,与序列化中的 fields 对应起来.
2.export_serializer_class 使用导出序列化器
class UserViewSet(CustomModelViewSet):
"""
用户接口
list:查询
create:新增
update:修改
retrieve:单例
destroy:删除
"""
queryset = Users.objects.exclude(is_superuser=1).all()
serializer_class = UserSerializer
create_serializer_class = UserCreateSerializer
update_serializer_class = UserUpdateSerializer
filter_fields = ['name','username','gender','is_active','dept']
search_fields = ['username','name','gender','dept__name','role__name']
#导出
export_field_label = ['用户账号', '用户名称','用户邮箱', '手机号码', '用户性别', '帐号状态', '最后登录时间', '部门名称', '部门负责人']
export_serializer_class = ExportUserProfileSerializer
#接口配置
re_path('user/export/', UserViewSet.as_view({'get': 'export_data', })),
import { request,downloadFile } from '@/api/service'
...
/**
* 导出
* @param params
*/
export function exportData (params) {
return downloadFile({
url:urlPrefix+'export/',
params:params
})
}
1.run_validation函数用于对数据进行格式转换
class UserProfileImportSerializer(CustomModelSerializer):
def save(self, **kwargs):
data = super().save(**kwargs)
password = hashlib.new('md5', self.initial_data.get('password', '').encode(encoding='UTF-8')).hexdigest()
data.set_password(password)
data.save()
return data
def run_validation(self, data={}):
# 把excel 数据进行格式转换
if type(data) is dict:
data['role'] = str(data['role']).split(',')
data['dept_id'] = str(data['dept']).split(',')
data['gender'] = {'男': '1', '女': '0', '未知': '2'}.get(data['gender'])
data['is_active'] = {'启用': True, '禁用': False}.get(data['is_active'])
return super().run_validation(data)
class Meta:
model = Users
exclude = ('password','post','user_permissions', 'groups', 'is_superuser', 'date_joined')
1.import_serializer_class为使用的导入序列化器
2.import_field_dict为字典格式,key为数据库的model字段,value为Excel表的表头列
class UserViewSet(CustomModelViewSet):
"""
用户接口
list:查询
create:新增
update:修改
retrieve:单例
destroy:删除
"""
queryset = Users.objects.exclude(is_superuser=1).all()
serializer_class = UserSerializer
create_serializer_class = UserCreateSerializer
update_serializer_class = UserUpdateSerializer
filter_fields = ['name','username','gender','is_active','dept']
search_fields = ['username','name','gender','dept__name','role__name']
#导出
export_field_label = ['用户账号', '用户名称','用户邮箱', '手机号码', '用户性别', '帐号状态', '最后登录时间', '部门名称', '部门负责人']
export_serializer_class = ExportUserProfileSerializer
#导入
import_serializer_class = UserProfileImportSerializer
import_field_dict = {'username': '登录账号', 'name': '用户名称', 'email': '用户邮箱', 'mobile': '手机号码',
'gender': '用户性别(男/女/未知)',
'is_active': '帐号状态(启用/禁用)', 'password': '登录密码', 'dept': '部门ID', 'role': '角色ID'}
#接口配置
re_path('user/import/',UserViewSet.as_view({'get': 'import_data', 'post': 'import_data'})),
<template>
<d2-container :class="{ 'page-compact': crud.pageOptions.compact }">
<d2-crud-x
ref="d2Crud"
v-bind="_crudProps"
v-on="_crudListeners"
>
<div slot="header">
<crud-search
ref="search"
:options="crud.searchOptions"
@submit="handleSearch"
/>
<el-button-group>
<el-button
size="small"
v-permission="'Create'"
type="primary"
@click="addRow"
><i class="el-icon-plus"/> 新增
</el-button>
<el-button
size="small"
v-permission="'Export'"
type="danger"
@click="onExport"
><i class="el-icon-download"/> 导出
</el-button>
<importExcel v-permission="'Import'" importApi="/api/system/user/import/">导入</importExcel>
</el-button-group>
<crud-toolbar
:search.sync="crud.searchOptions.show"
:compact.sync="crud.pageOptions.compact"
:columns="crud.columns"
@refresh="doRefresh()"
@columns-filter-changed="handleColumnsFilterChanged"
/>
</div>
</d2-crud-x>
</d2-container>
</template>
script
...
methods: {
getCrudOptions () {
return crudOptions(this)
},
pageRequest (query) {
return api.GetList(query)
},
addRequest (row) {
return api.createObj(row)
},
updateRequest (row) {
return api.UpdateObj(row)
},
delRequest (row) {
return api.DelObj(row.id)
},
onExport () {
this.$confirm('是否确认导出所有数据项?', '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(function () {
return api.exportData()
})
}
}
...
添加初始化菜单
"menu_button": [
...
{
"name": "导出",
"value": "Export",
"api": "/api/walking/activity/users_bind_enterprise/export/",
"method": 0
},
{
"name": "导入",
"value": "Import",
"api": "/api/walking/activity/users_bind_enterprise/import/",
"method": 0
}
...
]
捉个虫,api.js 的请求方法应该为 post
点下载模板的时候报错,是漏了哪里的配置吗?
qq 私发我吧
感觉我遇到的问题很奇葩,导入文件提示 File is not a zip file
{"code":4000,"data":null,"msg":"File is not a zip file"}
试了好久,模板不匹配居然提示的是 File is not a zip file 嗯 感觉它有自己的想法 哈哈
字典中配置的的性别是:
代码中的性别是:
这两者不一致
源码中和图片中的导出表标题字段不一样啊