Home > Blockchain >  How to allow users to download an excel file using python/Flask?
How to allow users to download an excel file using python/Flask?

Time:07-08

I have a method that takes in an excel file, read the excel file, extracts data from it and save. The issue I am having now is how to write a method that returns the excel file and allow users to download it from the frontend.

This is the main file

    class UploadFileForm(FlaskForm):
        file = FileField('File', validators=[InputRequired()])
        submit = SubmitField('Download File') 
    
    @app.route('/', methods=['GET', 'POST'])
    def home_api():
    
        form = UploadFileForm()
        if form.validate_on_submit():
    
            file = form.file.data
            file.save(os.path.join(os.path.abspath(os.path.dirname(_file_)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename)))
            process_xl(os.path.join(os.path.abspath(os.path.dirname(_file_)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename)))
            download_file(os.path.join(os.path.abspath(os.path.dirname(_file_)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename)))
    
            return 'File has been uploaded'
        return render_template('index.html', form=form)

This is the service that does the extraction and little manipulation.

from flask import send_file
import requests
from openpyxl import load_workbook


def weather(city):

    url = "https://community-open-weather-map.p.rapidapi.com/weather"
    querystring = {"q":f"{city}","lat":"0","lon":"0","callback":"test","id":"2172797","lang":"null","units":"imperial","mode":"HTML"}

    headers = {
        "X-RapidAPI-Key": "0a109dce92msh070cc32fb93c003p1e4e8djsnef8cf195fed1",
        "X-RapidAPI-Host": "community-open-weather-map.p.rapidapi.com"
    }

    response = requests.request("GET", url, headers=headers, params=querystring)

    return response.text

def process_xl(filename):

    wb = load_workbook(filename=filename)

    sheet_1 = wb['Sheet1']
    sheet_2 = wb['Sheet2']

    city_1 = sheet_1['A1'].value
    city_2 = sheet_2['']

Based on the requirement, I need a function that will return the excel file which I can call in the main method. I have tried returning the the excel file it was not working

CodePudding user response:

You only need to create a route that sends the file to the client

here is how

import os
from flask import send_file
@app.route('/downlaod')
def downloadExcel():
    root_path = "path_to_your_file"
    filename = "your_file_name.xlsx"
    file_path = os.path.join(root_path, filename)
    return send_file(file_path)

You function should save the file.

def process_xl(filename):

    wb = load_workbook(filename=filename)

    sheet_1 = wb['Sheet1']
    sheet_2 = wb['Sheet2']

    city_1 = sheet_1['A1'].value
    city_2 = sheet_2['']
    wb.save(filename)

CodePudding user response:

This line solved my problem

return send_from_directory('directory-path', file.filename)

This is the full code here

from flask import send_from_directory class UploadFileForm(FlaskForm): file = FileField('File', validators=[InputRequired()]) submit = SubmitField('Download File')

@app.route('/', methods=['GET', 'POST']) def home_api():

form = UploadFileForm()
if form.validate_on_submit():

    file = form.file.data
    file.save(os.path.join(os.path.abspath(os.path.dirname(_file_)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename)))
    process_xl(os.path.join(os.path.abspath(os.path.dirname(_file_)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename)))
    download_file(os.path.join(os.path.abspath(os.path.dirname(_file_)),app.config['UPLOAD_FOLDER'],secure_filename(file.filename)))

    return send_from_directory('directory-path', file.filename)
return render_template('index.html', form=form)
  • Related