Python 导出Excel
exportExcel.py
#! /usr/bin/python
#! -*- coding: utf-8 -*-
__auther__ = 'xiaoshenge'
import datetime,time
import sys
import MySQLdb
import xlrd
import xlwt
import calendar
import xlutils.copy
from util import test_local_db
#查询结果集,导出EXCEL
@test_local_db
def findResultData(db,start):
try:
sql='''
SELECT * FROM UV_ORDER WHERE CREATE_TIME = '%s'
''' % start
db.execute(sql)
result=db.fetchall()
return result
except Exception as e:
print str(e)
if __name__ == '__main__':
today = datetime.date(2017,7,26)
result = findResultData(today)
sheetname = str(today) + "uv订单"
#python 读取模板 导出Excel
rb = xlrd.open_workbook('D:\\uv_order.xlsx')
wb = xlutils.copy.copy(rb)
ws = wb.get_sheet(0) #获取sheet
ws.col(0).width = 256*13 #设置第一列的宽度
#python 导出Excel 2017-08-18
#wb = xlwt.Workbook()
#ws = wb.add_sheet(unicode(sheetname,'utf-8'))
#ws.col(0).width = 8000 #设置第一列的宽度
alignment = xlwt.Alignment() # Create Alignment
alignment.horz = xlwt.Alignment.HORZ_CENTER # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
alignment.vert = xlwt.Alignment.VERT_CENTER #May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM,
font0 = xlwt.Font()
font0.name = u'微软雅黑'
font0.bold = True
style_0 = xlwt.XFStyle()
style_0.font = font0
style_0.alignment = alignment
#设置单元格背景色
pattern= xlwt.Pattern()
pattern.pattern=1
pattern.pattern_fore_colour=44
style_0.pattern=pattern
style_a = xlwt.XFStyle()
style_a.alignment = alignment
style = xlwt.easyxf(num_format_str='#%')
style.alignment = alignment
rows = len(result)
for i in range(0,rows):
cols = result[i]
for j in range(0, len(cols)):
if not j : continue
ws.write(i+3, j-1, result[i][j], style_a)
#ws.write(i+3, j-1, result[i][j])
wb.save("d:\\1.xlsx") #保存
print "导出成功!"
#!/usr/bin/python
#! -*- coding: utf-8 -*-
__auther__ = 'shenshouwei'
import MySQLdb
def test_local_db(func):
def conn(*args, **kwargs):
conn = MySQLdb.connect(host='localhost',port=3306,user='root',passwd='123456',db='test',charset='utf8')
db = conn.cursor()
result = func(db, *args, **kwargs)
conn.commit()
conn.close()
return result
return conn