django導(dǎo)入excel文件使用pandas處理并批量插入

?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)

? ? ? ? 刪除第一行的標(biāo)題

獲取每列

? ? ? ? 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ù)進(jìn)行處理,從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ù)進(jìn)行轉(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) {

? ? ? ? ? ? ? }

? ? ? ? ? });

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容