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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值