Python MySQLdb 查询生成 Excel 文件

# encoding=utf-8
import os, sys, string, types, datetime
import MySQLdb
import xlwt
ezxf = xlwt.easyxf

reload(sys)
sys.setdefaultencoding('utf-8')

enddate = raw_input('请输入截止日期(YYYY-MM-DD):'.encode('gbk'))
try:
    d = enddate.split('-')
    datetime.date(int(d[0]), int(d[1]), int(d[2]))
except Exception, e:
    print '输入日期格式异常!'.encode('gbk')
    sys.exit()

# 参数设置
SERVER = '192.168.0.100'
USERNAME = 'root'
PASSWD = 'root'
DB = 'test'

# 当前路径
path = os.getcwd().decode('gbk').encode('utf-8')
rfile = u'测试_%s.xls' %enddate

# 定义格式
heading_xf = ezxf('font: bold on; align: wrap on, vert centre, horiz center;'
        'borders: left thin, right thin, top thin, bottom thin;'
        'pattern: pattern solid,fore_colour sky_blue;') # 表头格式
kinds = 'int text text text date money int money money int int int'.split() # 字段类型
col_width_px = (50, 60, 220, 320, 80, 100, 60, 100, 80, 60, 60, 80) # 每列列宽(像素)
kind_to_xf_map = {
        'date': ezxf('borders: left thin, right thin, top thin, bottom thin;', num_format_str='yyyy-mm-dd'),
        'int': ezxf('borders: left thin, right thin, top thin, bottom thin;', num_format_str='##0'),
        'money': ezxf('borders: left thin, right thin, top thin, bottom thin;', num_format_str='#,##0.00'),
        'text': ezxf('borders: left thin, right thin, top thin, bottom thin;')
        }
data_xfs = [kind_to_xf_map[k] for k in kinds]

# 连接数据库
try:
    conn = MySQLdb.connect(host = SERVER, user = USERNAME, passwd = PASSWD, db = DB, charset = 'utf8')
except :
    sys.exit()

# 获取 cursor 对象进行操作
#cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) # 使用字典cursor取得结果集
cursor = conn.cursor()
conn.cursor

# 查询 sql
sql = """ SELECT
                  number AS '编号', province AS '省份'
          FROM
                  test
          WHERE
                  date < %s """

# 获取查询结果
#cursor.execute("SET NAMES 'utf8'")
cursor.execute(sql, (enddate,))
data = cursor.fetchall()

# 创建工作簿及表单
book = xlwt.Workbook('utf-8')
sheet = book.add_sheet(u'测试', cell_overwrite_ok=True)

# 表字段名信息写入
header = cursor.description
rowx = 0
for colx, value in enumerate(header):
    sheet.write(rowx, colx, value[0], heading_xf)
    sheet.col(colx).width = int(col_width_px[colx] * 36.568) # 设置列宽 1px = 36.568

# 数据写入
if data:
    for rec in data:
        rowx += 1
        for colx, value in enumerate(rec):
            sheet.write(rowx, colx, value, data_xfs[colx])

# 写入最终文件
book.save(os.path.join(path, rfile))

# 关闭资源
cursor.close()
conn.close()

你可能感兴趣的:(Python)