前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<form method="post" enctype="multipart/form-data" action="http://127.0.0.1:5000/upload">
<input class="form-control" type="file" name="file_data" value="请上传excel文件">
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
后台代码
@app.route('/upload', methods=['POST'])
def his_upload_clinic_detail():
file_data = request.files.get('file_data')
if not file_data:
return '请上传文件'
# 这是将文件转为流,在xlrd中打开
workbook = xlrd.open_workbook(file_contents=file_data.read())
# sheet
sheet = workbook.sheet_by_index(0)
row_num = sheet.nrows
col_num = sheet.ncols
# 输出每一行的内容
# sheet.nrows获取该sheet中的有效行数
titles = ['name', 'age', 'high']
json_list = []
for i in range(row_num):
row_value = sheet.row_values(i)
obj = dict()
json_list.append(obj)
for title, col_val in zip(titles, row_value):
obj.setdefault(title, col_val)
print(json_list)
return json.dumps(json_list, ensure_ascii=False)