Open In App

How to create CSV output in Flask?

Last Updated : 29 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to create a CSV output using Flask. Python and Flask Web Frameworks provide powerful tools to generate a report, export data and create catalogs. We will see how to generate both CSV files using Python and Flask.

Creating CSV files in Python Flask

Step 1: Installation

We are using Flask to create CSV output. Please refer:- Install Flask and Install Python for proper installation.

Step 2: Create a Virtual Environment

In this step, we will first create a virtual environment for our project.

Step 3: Create Folders

Now, we will create a folder in the given format in the picture below. We will create a static folder and a template folder, and inside the template folder, create an index.html file. We will also create an app.py file where we will write our Python code.

Screenshot-from-2023-09-19-00-28-03

Step 4: Write Python Code

In this step, we will write our Flask logic in the form of Python code. Paste this code in your app.py file and save your file. In this code, we have made three routes, one for template rendering, one for generating data and other one for downloading the data in the form of CSV file.

Python3




from flask import Flask, render_template, request, Response, send_file
import csv
 
app = Flask(__name__)
 
# Sample data for demonstration
users = []
 
@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        name = request.form.get("name")
        email = request.form.get("email")
        users.append({"name": name, "email": email})
     
    return render_template("index.html", csv_data=users)
 
@app.route("/generate_csv")
def generate_csv():
    if len(users) == 0:
        return "No data to generate CSV."
 
    # Create a CSV string from the user data
    csv_data = "Name,Email\n"
    for user in users:
        csv_data += f"{user['name']},{user['email']}\n"
 
    return render_template("index.html", csv_data=csv_data)
 
@app.route("/download_csv")
def download_csv():
    if len(users) == 0:
        return "No data to download."
 
    # Create a CSV string from the user data
    csv_data = "Name,Email\n"
    for user in users:
        csv_data += f"{user['name']},{user['email']}\n"
 
    # Create a temporary CSV file and serve it for download
    with open("users.csv", "w") as csv_file:
        csv_file.write(csv_data)
 
    return send_file("users.csv", as_attachment=True, download_name="users.csv")
 
@app.route("/download_csv_direct")
def download_csv_direct():
    if len(users) == 0:
        return "No data to download."
 
    # Create a CSV string from the user data
    csv_data = "Name,Email\n"
    for user in users:
        csv_data += f"{user['name']},{user['email']}\n"
 
    # Create a direct download response with the CSV data and appropriate headers
    response = Response(csv_data, content_type="text/csv")
    response.headers["Content-Disposition"] = "attachment; filename=users.csv"
 
    return response
 
if __name__ == "__main__":
    app.run(debug=True)


Step 5: Write HTML Code

In this step, we will create a file index.html and paste this code inside that file. In this code, we have created an HTML form, and when a person writes his details. It is saved inside a CSV file.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSV Generator</title>
</head>
<body>
    <h1>CSV Generator</h1>
    <form method="POST" action="/">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br><br>
         
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br><br>
 
        <input type="submit" value="Generate CSV">
    </form>
 
    {% if csv_data %}
    <a href="/download_csv">
        <button>Download CSV</button>
    </a>
    {% endif %}
 
    {% if csv_data %}
    <div>
        <h2>Generated CSV:</h2>
        <pre>{{ csv_data }}</pre>
    </div>
    {% endif %}
</body>
</html>


Step 6: Run the file

In this step, just run the file and you will see this form. Just fill this form and a click on generate data. Data will be generated and then click on Download CSV button to download the file in CSV format.

Screenshot-from-2023-09-19-00-58-35

Data Format in CSV

Open the downloaded file and you will see the data in this format.

Screenshot-from-2023-09-19-00-58-55



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads