#-*-coding:utf-8-*-
import datetime, xlwt, os,pymysql
import yaml
import os
BASEPATH = os.path.dirname(__file__)
#读取数据库的配置(当前文件夹下的db.default.yaml)
def dbConfig():
stream = file(os.path.join(BASEPATH,'db.default.yaml'), 'r')
dicts = yaml.load(stream)
return dicts
# 获取当前日期做文件名
time = datetime.datetime.now().strftime('%Y-%m-%d')
# 获取execl保存的路径
file_path = os.path.abspath(os.path.join(os.path.dirname("__file__"))) + r"\execl\%s.xls" % time
# print file_path
def sava_execl(file_path):
# 获取前七天的时间
T1 = datetime.datetime.now().strftime('%Y-%m-%d')
T2 = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
T3 = (datetime.datetime.now() - datetime.timedelta(days=2)).strftime('%Y-%m-%d')
T4 = (datetime.datetime.now() - datetime.timedelta(days=3)).strftime('%Y-%m-%d')
T5 = (datetime.datetime.now() - datetime.timedelta(days=4)).strftime('%Y-%m-%d')
T6 = (datetime.datetime.now() - datetime.timedelta(days=5)).strftime('%Y-%m-%d')
T7 = (datetime.datetime.now() - datetime.timedelta(days=6)).strftime('%Y-%m-%d')
try:
# 链接数据库
option = dbConfig()['table_name'] # 获取连接的配置
host = option['host']
user = option['user']
passwd = option['passwd']
db = option['db']
conn = pymysql.connect(host=host, user=user, passwd=passwd, db=db, charset="utf8")
cur = conn.cursor()
# 读取数据模糊查询并排序
sql = """select * from cxf_tracking where datetime like '{}%'
or datetime like '{}%' or datetime like '{}%'
or datetime like '{}%' or datetime like '{}%'
or datetime like '{}%' or datetime like '{}%'
order by datetime
""".format(T1, T2, T3, T4, T5, T6, T7)
count = cur.execute(sql) # 查看前一个星期发布新闻的条数
fields = cur.description
results = cur.fetchall()
print results,
# results = results[:len(results)]
# print '有', len(results), '条数据要求推送',results
conn.commit()
cur.close()
# 写入execl表格
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('table_cxf_tracking', cell_overwrite_ok=True)
# 写上字段信息
for field in range(0, len(fields)):
sheet.write(0, field, fields[field][0])
# 在表格第一行写入mysql中字段的信息
# print field,fields[field][0],
# 获取并写入数据段信息
for row in range(1, len(results) + 1):
for col in range(0, len(fields)):
if (results[row - 1][col]) is not None:
sheet.write(row, col, u'%s' % results[row - 1][col])
try:
# 保存execl
workbook.save(r'{}'.format(file_path))
except Exception as e:
print u'已存在', e
pass
return
except Exception as e:
print e
pass
sava_execl(file_path)
Python写execl
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 成长记录-连载(三十六) ——我的第一篇五千字长文,说了什么,你一定想不到 并不是不想每天写公众号,而是之前思考怎...
- 写给想要入门python或者正在入门python的小朋友们: 写在前面:最近好像python挺火,虽然我也在天天写...
- 《web scraping with python》读书笔记1《web scraping with python》...