从MySQL数据库查询数据并写入excel
#! /bin/env python # encoding: utf-8 import xlwt import pymysql import datetime from mail import send_mail yestoday = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d") filename = "{}.xls".format((datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y%m%d")) conn = pymysql.connect(host="host", user="user",password="123123",database="db1",charset="utf8") cursor = conn.cursor() sql = """select * from t1 where t1.created_at> '{0} 00:00:00' order by xxx """.format(yestoday) book=xlwt.Workbook() sheet=book.add_sheet('sheet1') try: cursor.execute(sql) results = cursor.fetchall() for row_index,row in enumerate(results): for col_index,col in enumerate(row): sheet.write(row_index,col_index,col) except Exception as e: raise e finally: conn.close() book.save(filename)