版本一:將MySQL數據寫入到excel(xsl)文件並下載到默認文件夾(一般問電腦的下載文件夾里面),並顯示特效到前端頁面。
flask框架連接MySQL,我們使用pymsql這個工具,如下操作:
from flask import Flask import pymysql import xlwt from io import BytesIO from flask import make_response db = pymysql.connect(host='127.0.0.1',port=3306,user='user', passwd='pwd', db='db_name', charset='utf8') # 創建鏈接 def data_db(): # 去數據庫取數據,假設數據庫表只有4個字段 sql = """ select * from table_name; """ cc = db.cursor() # 其實就是用來獲得python執行Mysql命令的方法,也就是
我們所說的操作游標 cc.execute(sql) # 真正執行sql語句 cn = cc.fetchall() # 接收全部的返回結果行row return cn # 返回 app = Flask(__name__) @app.route('/index_up') # 設置路由 def index_list(): # 執行視圖函數 ret = data_db() # 獲取數據 wb = xlwt.Workbook(encoding='utf-8') # 實例化,有encoding和style_compression參數 ws = wb.add_sheet("111", cell_overwrite_ok=True) # Workbook的方法,生成名為111.xls文件 row0 = ['字段1', '字段2', '字段3', '字段4'] # 指定xls文件的字段 for i in range(0, len(row0)): # 將這些字段寫入111.xls文件 ws.write(0, i, row0[i]) k = 1 for i in ret: # 循環每一列 for j in range(4): # 在每列添加數據 ws.write(k, j, i[j])
k += 1 sio = BytesIO() # 將獲取的數據在內存中寫,有時會用到StringIO() wb.save(sio) # 將文件流保存 sio.seek(0) # 光標 response = make_response(sio.getvalue()) # response.headers['Content-type'] = 'application/vnd.ms-excel' # 指定返回的類型 response.headers['Transfer-Encoding'] = 'chunked' response.headers['Content-Disposition'] = 'attachment;filename=111.xls' # 設定用戶瀏覽器顯示的保存文件名 return response # 返回response,瀏覽器會出現如下效果,如果返回其他,比如None就會只下載不在瀏覽器提示。 if __name__ == '__main__': app.run()
版本二:將MySQL的數據寫入到excel中並下載到指定路徑里面
from flask import Flask import pymysql import xlwt from io import BytesIO from flask import make_response db = pymysql.connect(host='127.0.0.1',port=3306,user='user', passwd='pwd', db='db_name', charset='utf8') # 創建鏈接 def data_db(): # 去數據庫取數據,假設數據庫表只有4個字段 sql = """ select * from table_name; """ cc = db.cursor() # 其實就是用來獲得python執行Mysql命令的方法,也就是 我們所說的操作游標 cc.execute(sql) # 真正執行sql語句 cn = cc.fetchall() # 接收全部的返回結果行row return cn # 返回 app = Flask(__name__) @app.route('/index_up') # 設置路由 def index_list(): # 執行視圖函數 ret = data_db() # 獲取數據 wb = xlwt.Workbook(encoding='utf-8') # 實例化,有encoding和style_compression參數 ws = wb.add_sheet("111", cell_overwrite_ok=True) # Workbook的方法,生成名為111.xls文件 row0 = ['字段1', '字段2', '字段3', '字段4'] # 指定xls文件的字段 for i in range(0, len(row0)): # 將這些字段寫入111.xls文件 ws.write(0, i, row0[i]) k = 1 for i in ret: # 循環每一列 for j in range(4): # 在每列添加數據 ws.write(k, j, i[j]) k += 1 today = str(datetime.datetime.now()) file_name = "day_data" + today[0:13] + ".xls" fp = r"E:/我的資料/inner_ctrl01/ttt" wb.save(file_name) shutil.move(file_name, os.path.join(fp, file_name)) return 'ok' # 必須return,並且不能return 空 if __name__ == '__main__': app.run()