简体   繁体   English

如何通过http响应每次一次发送一个xls文件?

[英]How can I send an xls file one line per time through http 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? 如何修改我的代码以使其与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. 虽然,通过excel打开.csv文件时,链接页面中的第一个答案可以帮助我解决混乱的代码问题。 But as I commented, it would be a little inconvenient for the user. 但是,正如我评论的那样,这对于用户来说有点不便。 So I tried to export an .xls file directly. 因此,我尝试直接导出.xls文件。

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. 因为数据集非常大,所以我无法一次全部生成整个.xls文件,也许最好像我对.csv文件一样,一次向客户端发送一行或几行。

So how can I send the .xls data piece by piece to the client side? 那么如何将.xls数据逐段发送到客户端呢? or any better recommendations? 或任何更好的建议?

I would be really appreciated for your answer! 谢谢您的回答,我将不胜感激!

This is a possible solution using dependencies flask + sql-alchemy + pandas 这是使用依赖瓶+ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM