?django導(dǎo)入excel文件使用pandas處理并批量插入
導(dǎo)入庫:
import? pandas as pd
import xlwt
from io import BytesIO? #io數(shù)據(jù)流
?django視圖類
class ImportFarmerData(View):
? ? def post(self,request):
? ? ? ? excel_raw_data = pd.read_excel(request.FILES.get('file',''),header=None)
? ? ? ? 刪除第一行的標題
獲取每列
? ? ? ? excel_raw_data.drop([0,0],inplace=True)
? ? ? ? name_col = excel_raw_data.iloc[:,[0]]
? ? ? ? card_id_col = excel_raw_data.iloc[:,[1]]
? ? ? ? phone_col = excel_raw_data.iloc[:,[2]]
? ? ? ? area_num_col = excel_raw_data.iloc[:,[3]]
對每一列數(shù)據(jù)進行處理,從DataFrame類型轉(zhuǎn)換為list類型
? ? ? ? name_list = name_col.values.tolist()
? ? ? ? card_id_list = card_id_col.values.tolist()
? ? ? ? phone_list = phone_col.values.tolist()
對每一列的每一行的數(shù)據(jù)進行轉(zhuǎn)換著摔,轉(zhuǎn)換為str類型
? ? ? ? for i in range(len(name_list)):
? ? ? ? ? ? name_list_index = name_list[i]
? ? ? ? ? ? card_id_list_index = card_id_list[i]
? ? ? ? ? ? phone_list_index = phone_list[i]
? ? ? ? ? ? area_num_index = area_num_list[i]
? ? ? ? ? ? farmer_profile = FarmersProfile()
? ? ? ? ? ? farmer_profile.name = name_list_index[0]
? ? ? ? ? ? farmer_profile.card_id = card_id_list_index[0]
? ? ? ? ? ? farmer_profile.phone = phone_list_index[0]
? ? ? ? ? ? farmer_profile.area_num = area_num_index[0]
? ? ? ? ? ? farmer_profile.address_id = address.id
? ? ? ? ? ? farmer_profile.save()
? ? ? ? return HttpResponse(json.dumps({'code':'200','msg':'導(dǎo)入成功'})
? ? 由于前端使用leiui返回格式必須為json格式
?HTML:
<button type="button" class="layui-btn" id="test4" name="excel_data"><i class="layui-icon"></i>導(dǎo)入excel</button>
ajax:
layui.use('upload', function(){
? ? ? ? ? ? ? var $ = layui.jquery,
? ? ? ? ? ? ? ? ? upload = layui.upload;
? ? ? ? ? //指定允許上傳的文件類型
? ? ? ? ? upload.render({ //允許上傳的文件后綴
? ? ? ? ? ? ? elem: '#test4',
? ? ? ? ? ? ? type: 'post',
? ? ? ? ? ? ? url: '{% url 'users:import_famer' %}',
? ? ? ? ? ? ? accept: 'file', //普通文件,
? ? ? ? ? ? ? exts: 'xls', //只允許上傳壓縮文件,
? ? ? ? ? ? ? data: {'csrfmiddlewaretoken': '{{ csrf_token }}'},
? ? ? ? ? ? ? done: function(res) {
? ? ? ? ? ? ? ? if (res.code == 200 ) {
? ? ? ? ? ? ? ? ? ? layer.msg(res.msg);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ,error:function (res) {
? ? ? ? ? ? ? }
? ? ? ? ? });