開發(fā)版本:python2.7
@resource_manage.route("/batch_import_data", methods=["POST"]) # 接口形式
@auth_decorator.requires_auth # 驗(yàn)證用戶信息
def batch_import_data():
"""
批量導(dǎo)入
* file: 文件
* mode: is_device/is_station
:return:
"""
the_file = request.files.get("file")
mode = request.args.get('mode')
result = attribute_element_manager.batch_import_data(mode, the_file)
return make_response(jsonify(utility.convert_to_json(result)), 200)
將文件中的文字解讀成dict形式
def batch_import_data(mode, the_file):
"""
批量導(dǎo)入
:param mode: is_device/is_station
:param the_file:
:return:
"""
if the_file:
f = the_file.read()
data = xlrd.open_workbook(file_contents=f)
names = data.sheet_names() # 返回表格中所有工作表的名字
for sheet_name in names:
status = data.sheet_loaded(sheet_name) # 檢查sheet1是否導(dǎo)入完畢
if status is True:
table = data.sheet_by_name(sheet_name)
try:
keys = table.row_values(0) # 第一行作為key值
except Exception as e:
logging.error(e) # 表格中存在空sheet,或者第一行沒數(shù)據(jù)
continue
if keys:
rowNum = table.nrows # 獲取該sheet中的有效行數(shù)
colNum = table.ncols # 獲取該sheet中的有效列數(shù)
if rowNum == 0 or colNum == 0:
continue
else:
result = [] # 列表L存放取出的數(shù)據(jù)
for i in range(1, rowNum): # 從第二行(數(shù)據(jù)行)開始取數(shù)據(jù)
sheet_data = {} # 定義一個(gè)字典用來存放對應(yīng)數(shù)據(jù)
for j in range(colNum): # j對應(yīng)列值
sheet_data[keys[j]] = table.row_values(i)[
j] # 把第i行第j列的值取出賦給第j列的鍵值,構(gòu)成字典
result.append(sheet_data) # 一行值取完之后(一個(gè)字典),追加到L列表中
batch_import_data_translate_and_update(mode, result) # 這個(gè)方法就是拿到數(shù)據(jù)后的操作了
message = "success"
else:
message = "failed"
return message
開發(fā)期間遇到了一個(gè)問題,這個(gè)功能使用的是form-data格式傳輸?shù)奈募郧岸苏J(rèn)為content-type應(yīng)該寫上這個(gè)類型,于是就出現(xiàn)后端接口獲取不到file,file返回None,后來把前端的這個(gè)去掉后就可以接收數(shù)據(jù)了。
下面這個(gè)是網(wǎng)上的一個(gè)參考代碼:
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
