文件的下载
from flask import send_from_directory
@excel_bp.route('/get_attachment/<path:filename>')def get_attachment(filename): ???return send_from_directory(app.config['UPLOAD_FOLDER'],filename,as_attachment=True)
文件的上传
(1)html中
<input class="form-control" type="文件名" name="file" value="请上传excel文件">
(2)后端获取,保存
file = request.files.get('文件名') # 获取文件filename = file.filename ?# 获取文件名file.save(os.path.join(FILE_DIR,filename)) # 保存文件
(3)当然 要对文件名,文件类型进行判断;存储路径也要进行判断
可以使用werkzeug中的 secure_filename
判断文件类型
ALLOWED_EXTENSIONS = ['xls', 'xlsx']def allowe_file(filename): ???''' ???限制上传的文件格式 ???:param filename: ???:return: ???''' ???return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS
修改文件名
import osimport datetime,uuiddef change_filename(filename): ???''' ???修改文件名称 ???:param filename: ???:return: ???''' ???fileinfo = os.path.splitext(filename) ???filename = datetime.datetime.now().strftime("%Y%m%d%H%M%S")+str(uuid.uuid4().hex)+fileinfo[-1] ???return filename
判断储存路径
if not os.path.exists(FILE_DIR): ???os.makedirs(FILE_DIR)
python的excel操作
通过xlrd读文件
安装:pip install xlrd
通过 xlrd 打开excel,组装数据
import xlrddef get_data(filename,method='r'): ???''' ???改变数据结构 -- 方便前端显示 ???:param filename: ?文件名 ???:param method: ?按照 列或者 行 返回数据 ???''' ???data = xlrd.open_workbook(filename) ???table= data.sheets()[0] ???nrows = table.nrows ?# 行数 ???ncols = table.ncols ?# 列数 ???if method == 'r': ???????row_list = [ table.row_values(i) for i in range(0,nrows)] ??# 所有行的数据 ???????return row_list ???elif method == 'c': ???????col_list = [ table.col_values(i) for i in range(0,ncols)] ???# 所有列的数据 ???????return col_list
前端显示
< thead > ?????????< tr > ? ? ? ? ? ? ?{% for title in datalist[0] %} ? ? ? ? ? ? ? ? < th >{ title }< / th > ? ? ? ? ? ? ?{ % endfor % } ? ? ? ? ?< /tr > ???< / thead > ?????< tbody > ? ? ? ? ?{ % for row in datalist[1:] % } ? ? ? ? ? ? ?< tr > ??????????????????{ % for item in row % } ?????????????????????<td>{ { item } }</td> ?????????????????{ % endfor % } ?????????????< /tr > ? ? ? ? { % enfor % } ? ? ?< / tbody > ?< / table >