如何通过http响应每次发送一个xls文件一行? [英] How can I send an xls file one line per time through http response?
问题描述
问题
最近我遇到了导出大量数据的问题,并将其发送到客户端。
详细的问题描述显示在以下链接的页面中:
如何适应我的代码,使其兼容Microsoft Excel? / a>
页面帮助我解决打开 .csv 文件由excel时的凌乱代码的问题。但正如我所说,这将是一个小不方便的用户。因此,我尝试直接导出 .xls 文件。
由于数据集非常大,因此无法生成整个 .xls 文件一次,或许这是一个好主意,每次发送一行或几行到客户端,我用 .csv 文件。
那么如何将 .xls 数据逐条发送到客户端呢?或任何更好的建议?
我非常感谢您的回答! h2_lin>解决方案
这是一个可能的解决方案,使用dependencies flask + sql-alchemy + pandas
def export_query(query,file_name = None):
results = db.session.execute(query)
fetched = results.fetchall()
$ b b dataframe = pd.DataFrame(fetched)
dataframe.columns = get_query_coloumn_names(query)
base_path = current_app.config ['UPLOAD_FOLDER']
workingdocs = base_path + datetime.now()。strftime(%Y%m%d%H%M%S)+'/'
如果不是os.path.exists(workingdocs):
os.makedirs(workingdocs)
如果file_name是None:
file_name = workingdocs + str(uuid.uuid4())+' - '+'export.xlsx'
else:
file_name = workingdocs + file_name
dataframe.to_excel(file_name)
return file_name
def export_all(q,page_limit,page):
query = db.session.query(...)。\
outerjoin(..)。\
filter(..)。\
order_by(...)
paging_query = query.paginate(page,page_limit,True)
#TODO需要返回total以帮助用户继续尝试paging_query.total
return export_query )
@ api.route('/ export_excel /',methods = ['POST'])
@permission_required(Permission.VIEW_REPORT)
def export_excel $ b json = request.get_json(silent = False,force = True)
q =''.join(('%',json ['q'],'%'))
page_limit = try_parse_int (json ['page_limit'])
page = try_parse_int(json ['page'])
file_name = export_all(q,page_limit,page)
response = send_file )
response.headers [Content-Disposition] =附件; filename = export.xlsx
return response
Problem
Recently I got a problem with export large amount of data, and send it to the client side.
The detailed problem description shows in the linked page below:
How can I adapt my code to make it compatible to Microsoft Excel?
What's Different
Although, the first answer in the linked page help me to solve the problem of messy code when open the .csv file by excel. But as I commented, it would be a little inconvenient for the user. So I tried to export an .xls file directly.
My Question Is
Because the dataset is quite large, I cannot generate the whole .xls file all at once, maybe it's a good idea to send one line or several lines to the client side per time as I did with the .csv file.
So how can I send the .xls data piece by piece to the client side? or any better recommendations?
I would be really appreciated for your answer!
This is a possible solution using dependencies flask + sql-alchemy + pandas
def export_query(query, file_name = None):
results = db.session.execute(query)
fetched = results.fetchall()
dataframe = pd.DataFrame(fetched)
dataframe.columns = get_query_coloumn_names(query)
base_path = current_app.config['UPLOAD_FOLDER']
workingdocs = base_path + datetime.now().strftime("%Y%m%d%H%M%S") + '/'
if not os.path.exists(workingdocs):
os.makedirs(workingdocs)
if file_name is None:
file_name = workingdocs + str(uuid.uuid4()) + '-' + 'export.xlsx'
else:
file_name = workingdocs + file_name
dataframe.to_excel(file_name)
return file_name
def export_all(q, page_limit, page):
query = db.session.query(...).\
outerjoin(..).\
filter(..).\
order_by(...)
paging_query = query.paginate(page, page_limit, True)
# TODO need to return total to help user know to keep trying paging_query.total
return export_query(paging_query)
@api.route('/export_excel/', methods=['POST'])
@permission_required(Permission.VIEW_REPORT)
def export_excel():
json = request.get_json(silent=False, force=True)
q = ''.join(('%',json['q'],'%'))
page_limit = try_parse_int(json['page_limit'])
page = try_parse_int(json['page'])
file_name = export_all(q, page_limit, page)
response = send_file(file_name)
response.headers["Content-Disposition"] = "attachment; filename=export.xlsx"
return response
这篇关于如何通过http响应每次发送一个xls文件一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!