Upload and Read Excel File in Flask
In this article, we will look at how to read an Excel file in Flask. We will use the Python Pandas library to parse this excel data as HTML to make our job easier. Pandas additionally depend on openpyxl library to process Excel file formats. Before we begin, make sure that you have installed both Flask and Pandas libraries along with the openpyxl dependency.
Required Module:
pip install flask==2.2.2 pip install pandas==1.4.2 pip install openpyxl==3.0.10
File Structure
Please make sure that you name the HTML file as ‘upload-excel.html’ and place it in the ‘templates’ folder within the root directory of the application.
HTML Template
Create the HTML template which will render the user interface to view the Browse and Upload options for the file. We have allowed uploading of MS Excel and Open XML formats only through the accepted attribute of the input tag.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < title >Upload/View Excel</ title > </ head > < body > < h1 >Upload Excel File (.xlsx)</ h1 > < form action = "{{ url_for('view') }}" method = "post" enctype = "multipart/form-data" > < input type = "file" name = "file" accept = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" > < input type = "submit" value = "Upload" > </ form > </ body > </ html > |
Upload and Read Excel File in Flask
Step 1: Upload Excel File in Flask
Import the required module
Python3
# Importing required functions import pandas from flask import Flask, render_template, request |
Step 2: Read Excel File in Flask
This Function returns the index page to upload the Excel file.
Python3
# Root endpoint @app .get( '/' ) def upload(): return render_template( 'upload-excel.html' ) |
Step 3:
Here, we have created the Flask App which will contain two endpoints. One endpoint will handle a GET request from the root URL. This will return the HTML template which contains the option to upload files. The other endpoint is ‘/view’ which handles POST requests. This will read the upload file and return the HTML snippet to view the uploaded Excel in tabular format in the browser window. Also, the file will save in your local directory using the function save().
Python3
# Importing required functions import pandas from flask import Flask, render_template, request from fileinput import filename # Flask constructor app = Flask(__name__) # Root endpoint @app .get( '/' ) def upload(): return render_template( 'upload-excel.html' ) @app .post( '/view' ) def view(): # Read the File using Flask request file = request.files[ 'file' ] # save file in local directory file .save( file .filename) # Parse the data as a Pandas DataFrame type data = pandas.read_excel( file ) # Return HTML snippet that will render the table return data.to_html() # Main Driver Function if __name__ = = '__main__' : # Run the application on the local development server app.run(debug = True ) |
python main.py
Output:
Contact Us