Python從資料庫匯出資料成excel
阿新 • • 發佈:2018-12-11
from trump.db import query from utils.result_process import success,aborted import xlwt import datetime import config_business from sanic import response from utils.data_to_execl_sunge import excel_style async def post(app,request): params = request.json if "sql_str" not in params: return aborted(return_msg="缺少必傳引數!") sql_str = params.get("sql_str") if sql_str.__contains__('insert') or sql_str.__contains__('update') or sql_str.__contains__('delete') : return aborted(return_msg="親,只能輸入查詢語句喲!") try: data = await query(app.pool, sql_str, fetch_type='fetch') fields_object = await query(app.pool, sql_str, fetch_type='attributes') head_message = [] for k,v in fields_object.items(): head_message.append(k) wbk = xlwt.Workbook() sheet = wbk.add_sheet('Sheet1', cell_overwrite_ok=True) header01, style_COL_AC = excel_style() tall_style = xlwt.easyxf('font:height 400;') today_date = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S") if data: for k, v in enumerate(data[0]): sheet.write(0, k, head_message[k], header01) for i in range(len(data)): sheet.row(i).set_style(tall_style) for key, item in enumerate(data[i]): sheet.write(i + 1, key, data[i][item], style_COL_AC) sheet.col(key).width = 240 * 20 wbk.save(config_business.EXCEL_SAVE_PATH + 'query_sql_' + str(today_date) + '.XQ要查詢的資料' +'.xls') # return await response.file(config_business.EXCEL_SAVE_PATH + 'query_orders_' + str(today_date) + '.xls', # mime_type='application/vnd.ms-excel', # headers={"Content-Disposition": "attachment; filename=徐倩資料查詢.xls"}) return success(config_business.EXCEL_SAVE_PATH + 'query_sql_' + str(today_date) + '.XQ要查詢的資料' +'.xls') else: return aborted(return_msg="沒有查詢到任何資料!") except Exception as err: return aborted(err)