flask 对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="請(qǐng)上傳excel文件">(2)后端獲取,保存
file = request.files.get('文件名') # 獲取文件
filename = file.filename # 獲取文件名
file.save(os.path.join(FILE_DIR,filename)) # 保存文件
(3)當(dāng)然 要對(duì)文件名,文件類型進(jìn)行判斷;存儲(chǔ)路徑也要進(jìn)行判斷
可以使用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 os
import datetime,uuid
def 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
判斷儲(chǔ)存路徑
if not os.path.exists(FILE_DIR):
os.makedirs(FILE_DIR)
?
python的excel操作
?
通過xlrd讀文件
安裝:pip install xlrd
通過 xlrd 打開excel,組裝數(shù)據(jù)
import xlrd
def get_data(filename,method='r'):
'''
改變數(shù)據(jù)結(jié)構(gòu) -- 方便前端顯示
:param filename: 文件名
:param method: 按照 列或者 行 返回?cái)?shù)據(jù)
'''
data = xlrd.open_workbook(filename)
table= data.sheets()[0]
nrows = table.nrows # 行數(shù)
ncols = table.ncols # 列數(shù)
if method == 'r':
row_list = [ table.row_values(i) for i in range(0,nrows)] # 所有行的數(shù)據(jù)
return row_list
elif method == 'c':
col_list = [ table.col_values(i) for i in range(0,ncols)] # 所有列的數(shù)據(jù)
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寫文件
總結(jié)
以上是生活随笔為你收集整理的flask 对excel上传下载操作和文件处理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新手起步:通达信怎么编写指标公式以及通达
- 下一篇: 入职新的工作