Upload, read, write excel file in Python flask

20,689

I guess a barebones version of what you wanted would be this. But this would obviously require more work.

from flask import Flask, request, jsonify
import pandas as pd

app=Flask(__name__)

@app.route("/upload", methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        print(request.files['file'])
        f = request.files['file']
        data_xls = pd.read_excel(f)
        return data_xls.to_html()
    return '''
    <!doctype html>
    <title>Upload an excel file</title>
    <h1>Excel file upload (csv, tsv, csvz, tsvz only)</h1>
    <form action="" method=post enctype=multipart/form-data>
    <p><input type=file name=file><input type=submit value=Upload>
    </form>
    '''

@app.route("/export", methods=['GET'])
def export_records():
    return 

if __name__ == "__main__":
    app.run()
Share:
20,689
vinita
Author by

vinita

Updated on June 14, 2020

Comments

  • vinita
    vinita almost 4 years

    Im using this code which asks user to upload a file, which I want to be read into a dataframe. Then this dataframe should be displayed as output on the page.

    What should I write in the return, so as to accomplish this ?

    from flask import Flask, request, jsonify
    import flask_excel as excel
    import pandas as pd
    
    app=Flask(__name__)
    
    @app.route("/upload", methods=['GET', 'POST'])
    def upload_file():
        if request.method == 'POST':
            return jsonify({"result": request.get_array(field_name='file')})
        return '''
        <!doctype html>
        <title>Upload an excel file</title>
        <h1>Excel file upload (csv, tsv, csvz, tsvz only)</h1>
        <form action="" method=post enctype=multipart/form-data>
        <p><input type=file name=file><input type=submit value=Upload>
        </form>
        '''
    
    @app.route("/export", methods=['GET'])
    def export_records():
        return 
    
    if __name__ == "__main__":
        app.run()