開發版本:python2.7
@resource_manage.route("/batch_import_data", methods=["POST"]) # 接口形式
@auth_decorator.requires_auth # 驗證用戶信息
def batch_import_data():
"""
批量導入
* 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):
"""
批量導入
: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是否導入完畢
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,或者第一行沒數據
continue
if keys:
rowNum = table.nrows # 獲取該sheet中的有效行數
colNum = table.ncols # 獲取該sheet中的有效列數
if rowNum == 0 or colNum == 0:
continue
else:
result = [] # 列表L存放取出的數據
for i in range(1, rowNum): # 從第二行(數據行)開始取數據
sheet_data = {} # 定義一個字典用來存放對應數據
for j in range(colNum): # j對應列值
sheet_data[keys[j]] = table.row_values(i)[
j] # 把第i行第j列的值取出賦給第j列的鍵值,構成字典
result.append(sheet_data) # 一行值取完之后(一個字典),追加到L列表中
batch_import_data_translate_and_update(mode, result) # 這個方法就是拿到數據后的操作了
message = "success"
else:
message = "failed"
return message
開發期間遇到了一個問題,這個功能使用的是form-data格式傳輸的文件,所以前端認為content-type應該寫上這個類型,于是就出現后端接口獲取不到file,file返回None,后來把前端的這個去掉后就可以接收數據了。
下面這個是網上的一個參考代碼:
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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