flask上传数据到mysql_flask 上传Excel 到数据库

前端

后端

import xlrd

import pymysql

# 建立数据库连接

def sql_func(sql_command):

conn = pymysql.connect(

host = "39.107.24.78",

port = 3306,

user = "root",

password = "123456",

charset = "utf8",

database = "flask_test"

)

cursor = conn.cursor(pymysql.cursors.DictCursor) # pymysql.cursors.DictCursor 以列表套字典形式返回,默认以元组套元组返回

sql = sql_command

cursor.execute(sql)

conn.commit()

conn.close()

def execl_input(info):

# 找到文件

# xls = xlrd.open_workbook("/Users/liuguixiang/Documents/excel_test.xlsx") # 指定文件路径

xls = xlrd.open_workbook(file_contents=info) # 指定文件内容

# 确定工作表

sheet = xls.sheet_by_name("sheet1")

# 遍历文件

for i in range(2,sheet.nrows): # 注意数据是从第几行开始的

title = sheet.cell(i,0).value # 取第i行,第0列,以此类推

price = sheet.cell(i,1).value

auther = sheet.cell(i,2).value

sql_command = "insert into book (title,price,auther) values ('%s',%s,'%s')" %(title, price, auther)

sql_func(sql_command)

要从 MySQL 数据库获取数据并将其导出到 Excel,你可以使用 FlaskMySQL Connector 和 openpyxl 库。以下是一个简单的示例代码: ```python from flask import Flask, make_response import mysql.connector from openpyxl import Workbook app = Flask(__name__) @app.route('/export-excel') def export_excel(): # 连接到 MySQL 数据库 conn = mysql.connector.connect( host='localhost', user='root', password='password', database='database' ) # 从数据库获取数据 cursor = conn.cursor() cursor.execute('SELECT * FROM table') data = cursor.fetchall() # 创建一个 Workbook 对象 wb = Workbook() # 选择默认的工作表 ws = wb.active # 将数据添加到工作表 for row in data: ws.append(row) # 将 Workbook 对象保存到内存 output = BytesIO() wb.save(output) # 创建一个响应对象并将 Excel 文件作为附件添加到响应 response = make_response(output.getvalue()) response.headers['Content-Disposition'] = 'attachment; filename=example.xlsx' response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # 关闭数据库连接并返回响应 cursor.close() conn.close() return response if __name__ == '__main__': app.run() ``` 在上面的代码,我们首先连接到 MySQL 数据库,并从表获取数据。然后,我们创建一个 Workbook 对象,并将数据添加到工作表。接下来,我们将 Workbook 对象保存到内存,并创建一个响应对象,将 Excel 文件作为附件添加到响应。最后,我们关闭数据库连接并返回响应。请根据需要更改代码数据库连接和查询语句。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值