본문 바로가기
웹 프로그래밍

[Flask] 디비 내용 엑셀 다운로드 기능

by Ratataca 2023. 5. 16.
from flask import Flask, make_response
import mysql.connector
import pandas as pd

app = Flask(__name__)

# MariaDB 연결 설정
db = mysql.connector.connect(
    host="localhost",
    user="your_username",
    password="your_password",
    database="your_database"
)

@app.route('/download_excel')
def download_excel():
    # 쿼리를 실행하여 데이터 가져오기
    cursor = db.cursor()
    query = "SELECT * FROM your_table"
    cursor.execute(query)
    result = cursor.fetchall()

    # 판다스 데이터프레임 생성
    df = pd.DataFrame(result, columns=[i[0] for i in cursor.description])

    # 엑셀 파일 생성
    excel_file = df.to_excel(index=False)

    # 응답 객체 생성
    response = make_response(excel_file)
    response.headers[
        "Content-Disposition"] = "attachment; filename=your_data.xlsx"
    response.headers["Content-type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

    # 연결과 커서 닫기
    cursor.close()
    db.close()

    return response

if __name__ == '__main__':
    app.run()

댓글