批量導入excel文件中的數據,咱們須要藉助xlrd模塊,示例以下:html
視圖代碼:數據庫
import xlrd def multi_view(self,request): """ 批量導入 :param request: :return: """ if request.method == 'GET': return render(request,'multi_view.html') else: file_obj = request.FILES.get('exfile') with open('xxxxxx.xlsx',mode='wb') as f: for chunk in file_obj: f.write(chunk) workbook = xlrd.open_workbook('xxxxxx.xlsx') sheet = workbook.sheet_by_index(0) #拿到excel中的第一個文件薄 maps = { 0:'name', 1:'qq', } #maps是關於excel表中應該有的字段和字段順序 for index in range(1,sheet.nrows): #對數據行進行循環(不包含第一行的字段行) row = sheet.row(index) #得到行的列對象 row_dict = {} for i in range(len(maps)): key = maps[i] cell = row[i] row_dict[key] = cell.value #cell.value得到列中的內容 print(row_dict) #將數據錄入數據庫,如:UserInfo.objects.create(**row_dict) return HttpResponse('上傳成功')
頁面代碼:post
{% extends 'stark/layout.html' %} {% block body %} <h1 >批量導入數據</h1> {# 爲了用戶批量上傳的文件數據按照咱們視圖代碼中要求的那些字段格式,咱們能夠提供這樣的模板excel#} <a href="/static/xxx.xlsx">下載模板</a> <form method="post" enctype="multipart/form-data" class="form-horizontal" novalidate> {% csrf_token %} <input type="file" name="exfile"> <input type="submit" value="提交"> </div> </form> {% endblock %}