django导入excel,离开小厂进大厂的第一周

:return:

“”"

===================== 1.接收Excel文件存储到media文件夹 =======================

rev_file = request.FILES.get(‘excel’)

判断,是否有文件

if not rev_file:

return JsonResponse({‘code’: 500, “message”: “上传文件不能为空”})

获得一个唯一名字:uuid +hash

new_name = get_random_str()

准备写入URL

file_path = os.path.join(settings.MEDIA_ROOT, new_name + os.path.splitext(rev_file.name)[1])

开始写入本地磁盘

try:

f = open(file_path, ‘wb’)

多次写入

for i in rev_file.chunks():

f.write(i)

写完之后要关闭

f.close()

except Exception as e:

return JsonResponse({‘code’: 500, “message”: “文件上传失败:” + str(e)})

===================== 2.读取存储在Media文件夹的数据 =====================

ex_students = read_excel_dict(file_path)

===================== 3.把读取的数据存储到数据库 =====================

success = 0

error = 0

error_snos = []

print(len(ex_students))

print(ex_students)

for one_student in ex_students:

try:

这里是先更新,后增加

obj_student = Student(sno=one_student[‘sno’], name=one_student[‘name’],

gender=one_student[‘gender’], birthday=one_student[‘birthday’],

mobile=one_student[‘mobile’], email=one_student[‘email’],

address=one_student[‘address’])

这里是直接增加

obj_student = Student.objects.create(sno=one_student[‘sno’], name=one_student[‘name’],

gender=one_student[‘gender’], birthday=one_student[‘birthday’],

mobile=one_student[‘mobile’], email=one_student[‘email’],

address=one_student[‘address’])

obj_student.save()

计数

success += 1

except Exception as e:

error += 1

error_snos.append(one_student[‘sno’])

===================== 4.返回——导入信息 =====================

return JsonResponse(

{‘code’: 200, “data”: {“success”: success, “error”: error, “info”: error_snos}, “message”: “操作成功”})

def read_excel_dict(path: str):

“”"

读取excel数据

:param path:

:return:

“”"

实例化一个wrokbook

wrokbook = openpyxl.load_workbook(path)

实例化一个sheet(‘student’:指的是默认读取student表格)

sheet = wrokbook[‘student’]

定义一个变量存储最终的数据

students = []

准备key

keys = [‘sno’, ‘name’, ‘gender’, ‘birthday’, ‘mobile’, ‘email’, ‘address’]

遍历

for row in sheet.rows:

定义一个临时的字典

temp_dict = {}

组合值和key

for index, cell in enumerate(row):

组合

if keys[index] == ‘sno’ and cell.value is None:

break

temp_dict[keys[index]] = cell.value

附加到list中

if temp_dict:

students.append(temp_dict)

返回

if len(students) > 0:

return students[1:]

else:

return students

  • urls.py配置

urlpatterns = [

url(路径,视图)

url(r’^students/importStudentExcel/$’, views.import_student_excel)

]

  • 前端代码

<el-upload

action=""

:show-file-list="

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享

false"

:http-request=“uploadExcelPost”

导入Excel

const Api = {

ImportStudentExcel:’/student/students/importStudentExcel/’,

}

/**

  • 导入Excel

  • json请求

  • @param parameter

  • @returns {*}

*/

export function importStudentExcel(parameter) {

return request({

url: Api.ImportStudentExcel,

method: ‘post’,

// data: qs.stringify(parameter)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值