分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

flask 文件的上传下载和excel操作

发布时间:2023-09-06 01:48责任编辑:胡小海关键词:excel


文件的下载

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 >

通过xlwt写文件

flask 文件的上传下载和excel操作

原文地址:https://www.cnblogs.com/big-handsome-guy/p/8715312.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved