python自動生成excel報表

1.將SQL語句查詢的內容,直接寫入到excel報表中,如下爲所有腳本。
要求:此版本必須運維在windows平臺,而且安裝了excel程序,excel版本不限。
   python版本爲2.7
   if b    判斷b是否爲空值

在execl中,列和行都是以0開始
【0】 0 1 2 3
【1】 0   1    2   3

sql語句要求,若是sql語句的條件須要外部傳入進去,那麼sql語句必須用""號括起來
# -*- coding:utf-8 -*-
from xlwt import *
import xlrd
import pymysql

#創建mysql鏈接 conn
= pymysql.connect(host='127.0.0.1',user='root', passwd='1234', db='test', charset='utf8') cur = conn.cursor() def SQL(cur,sql): cur.execute(sql); return (cur);
#執行sql語句 a
=SQL(cur, r"select * from test;")

#打開一個execle文檔 w
= Workbook(encoding='utf-8') ws= w.add_sheet(u"xls")
i
=1 f = ['id', '名字']
#經過循環,將列明插入進去。 g
= 0 for x in f: fnt = Font() style = XFStyle() style.font = fnt ws.write(0, g, x) ws.row(i).set_style(style) g = g + 1 try:
   #遍歷sql語句查詢到的內容
for b in a: fnt = Font() style = XFStyle() style.font = fnt for f in range(0,len(b)): ws.write(i, f, '%s' %b[f]) ws.row(i).set_style(style) i = i + 1 if b: w.save(u"測試.xls") except Exception as e: print(e) cur.close() conn.close()
相關文章
相關標籤/搜索