python自动生成excel报表

时间:2024-09-18 16:35:02
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='', 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()