HTML的代码:
效果如下:
JavaScript的代码:
function import_elder_information() {
if($('#CONTENTS').val == '')
{
swal('请选择导入文件!');
return false;
}
var formData = new FormData();
formData.append("content",$('#CONTENTS')[0].files[0]);
$.ajax({
url: '/sqb/management_living/living_elder/nursing_record/import_record',
dataType: 'json',
async: false,
data:formData,
type: 'post',
processData : false, // 使数据不做处理
contentType : false, // 不要设置Content-Type请求头
success: function (data) {
console.log(data);
alert('导入成功');
},
error: function (data) {
alert('error');
}
})
}
Ajax上传文件就这么写就对了
Python的代码:
import openpyxl
@sqb.route('/import_user', methods=['GET', 'POST'])
def import_record(*_arg, **_kwarg):
try:
result = []
CONTENTS = request.files.get('content')
# # 打开excel文件,获取工作簿对象
# # wb = openpyxl.load_workbook('F:/info.xlsx')
if CONTENTS:
folder_url = 'excel'
result = upload_files_by_folder_name(CONTENTS, folder_url)
if 'error' in result[0]:
print(result[0]['error'])
else:
url = result[0]['dirname'] + '/' + result[0]['filename']
else:
return 0
wb = openpyxl.load_workbook(url)
# 从表单中获取单元格的内容
sheet = wb['数据录入'] # 当前表单
#从第二行开始读取数据,因为第一行是标题
for i in range(2, sheet.max_row):
#列是从1开始的
elder_name = sheet.cell(i, 1).value # 老人姓名
age= sheet.cell(i, 2).value # 年龄
#插入数据库,自己写,写法不一样
insert_sql = """insert into user(name,age) values(%s,%s)"""
db_helper.updateSql(insert_sql,pargm=[name, age])
result.append(elder_name)
result = json.dumps(result)
return result
except Exception as exc:
ex_str = traceback.format_exc()
logger.error('error', exc_info=True)
resp = make_response(render_template('error.html', errormsg=exc, hot_line=hot_line,copy_right=copy_right))
return resp
def upload_files_by_folder_name(file_obj, folder_url):
"""
文件上传
:param file_obj:
:param folder_url:
:return:
"""
error = False
result = []
if file_obj and upload_allowed_file(file_obj.filename):
fname, fext = os.path.splitext(file_obj.filename)
rnd_name = '%s%s' % (gen_rnd_filename(), fext)
filepath = os.path.join(sqb.static_folder, 'upload/%s' % folder_url, rnd_name)
# 检查路径是否存在,不存在则创建
dirname = os.path.dirname(filepath)
if not os.path.exists(dirname):
try:
os.makedirs(dirname)
except:
error = 'ERROR_CREATE_DIR'
elif not os.access(dirname, os.W_OK):
error = 'ERROR_DIR_NOT_WRITEABLE'
if error:
result.append({'error': error})
else:
file_obj.save(filepath)
url = 'http://' + get_env('domain_name') + '/upload/%s/%s' % (folder_url, rnd_name)
result.append({"filename": rnd_name, "url": url,"dirname":dirname})
return result
excel的表格就如下所示:
这样基本就完成了一个简单的python导入