在mac os 系统上使用python处理excel工作周报
.日期处理(包括时间格式、几天前的日期)
.excel处理(包括copy生成新excel,修改sheet名称)
.汉字处理(字符编码)
.定时任务
.开机启动任务
定时任务和开机启动任务开发中..............
0.install pip
$sudo easy_install pip
1.install openpyxl
python version 2.7.9 or later
$sudo pip install openpyxl
2.日期处理
MyDate.py
#!/usr/bin/python
from datetime import datetime, timedelta
import time
class MyDate:
def __init__(self):
self.now = datetime.now()
# return data type:date
def getNDaysAgo(self,daysAgo):
return self.now - timedelta(days=daysAgo)
# return data type:int
def getYear(self):
return self.now.year
# return data type:int
def getMonth(self):
return self.now.month
# return data type:int
def getDay(self):
return self.now.day
# return data type:int
def getHour(self):
return self.now.hour
# return data type:int
def getMintue(self):
return self.now.minute
# return data type:int
def getSecond(self):
return self.second
# return data type:string
# myForamt '%s-%s-%s'
def getYearMonthDayFormat(self,myFormat):
return (myFormat %(self.now.year,self.now.month,self.now.day))
# return data type:string
# myForamt '%s-%s-%s'
def getHourMintueSecondFormat(self,myFormat):
return (myFormat %(self.now.hour,self.now.minute,self.now.second))
#default date type
def getDate(self):
return self.getYearMonthDayFormat('%s-%s-%s')
#default time type
def getTime(self):
return self.getHourMintueSecondFormat('%s:%s:%s')
## dd/mm/yyyy format
def getStrFormatTime(self,timeFormat):
return self.now.strftime(timeFormat)
def getFormatWithDate(self,date,timeFormat):
return date.strftime(timeFormat)
def test(self):
i = self.now
print 'Test class of MyDate:'
print ("Current date & time = %s" % i)
print ("Date and time in ISO format = %s" % i.isoformat() )
print ("Current year = %s" %i.year)
print ("Current month = %s" %i.month)
print ("Current date (day) = %s" %i.day)
print ("dd/mm/yyyy format = %s/%s/%s" % (i.day, i.month, i.year) )
print ("Current hour = %s" %i.hour)
print ("Current minute = %s" %i.minute)
print ("Current second = %s" %i.second)
print ("hh:mm:ss format = %s:%s:%s" % (i.hour, i.month, i.second) )
print ('getYear:%s' %self.getYear())
#print 'month:'+self.getMonth()
print 'date foramt:'+self.getYearMonthDayFormat("%s-%s-%s")
print '7 days before today:'
print self.getFormatWithDate(self.getNDaysAgo(7),'%Y-%m-%d')
print 'today:'+self.getStrFormatTime('%Y/%m/%d %H:%M:%S')
if __name__ == '__main__':
myDate = MyDate()
myDate.test()
3.excel处理
1)从template.xlsx 另存为目标excel
2)修改sheet的名字为目标sheet
dowsr.py
#!/usr/bin/python
#-*-coding:utf-8 -*-
import openpyxl
from openpyxl import Workbook
from MyDate import MyDate
class DoWsr:
dateFormat = '%Y%m%d'
nameFormat = u'Android_xxx_工作周报(%s-%s).xlsx'
sheetNameFormat = u'周报%s.%s-%s.%s'
excelPath = '.'
templateName = 'template_wsr.xlsx'
date = MyDate()
#sppose today is Friday
today = date.getStrFormatTime(dateFormat)
thisWeekFirstDay = date.getFormatWithDate(date.getNDaysAgo(4),dateFormat)
newName = (nameFormat %(thisWeekFirstDay,today))
newDate = (sheetNameFormat %(date.getNDaysAgo(4).month,date.getNDaysAgo(4).day,date.getMonth(),date.getDay()))
#lastWeekFirstDay = date.getYearMonthDayWithDateFormat(date.getNDaysAgo(11),dateFormat)
#lastFriday = (dateFormat %(date.getYear(),date.getMonth(),(date.getDay()-7)))
#excleName = (nameFormat %(lastWeekFirstDay,lastFriday))
def __init__(self):
print 'wrok start:'+self.date.getStrFormatTime('%Y/%m/%d %H:%M:%S')
def createNewExcel(self,excelName,sheetName):
print 'excelName:'+excelName.encode('utf-8')
print 'sheetName:'+sheetName.encode('utf-8')
templateExcel = openpyxl.load_workbook(self.excelPath+'/'+self.templateName)
print 'load workbook over..'
sheet = templateExcel.active
sheet.title = sheetName
print 'set sheet over...'
templateExcel.save(self.excelPath+'/'+excelName)
print 'save workbook over...'
def doJob(self):
print self.newName.encode('utf-8')
self.createNewExcel(self.newName,self.newDate)
if __name__ == '__main__':
doWsr = DoWsr()
print 'dojob...'
doWsr.doJob()
print 'dojob over'
commandline执行dowsr.py正常,pipline执行会出现错误:UnicodeEncodeError: 'ascii' codec can't encode character ,将带有汉字的变量打印到屏幕时会出现,解决办法是.encode('utf-8')
4.定时任务
4.1 编辑crontab
1.In Terminal: crontab -e.
2.Press i to go into vim's insert mode.
3.Type your cron job, for example:
30 * * * * /usr/bin/curl --silent --compressed http://example.com/crawlink.php
4.Press Esc to exit vim's insert mode.
5.Type ZZ to exit vim (must be capital letters).
6.You should see the following message: crontab: installing new crontab. You can verify the crontab file by using crontab -l.
4.2模拟立即运行crontab
1.Add the following line to the crontab, e.g. using crontab -e
* * * * * /usr/bin/env > /home/username/cron-env
2.Create a shell script which executes a command in the same environment as cron jobs run:
run-as-cron.sh
#!/bin/sh
. "$1"
exec /usr/bin/env -i "$SHELL" -c ". $1; $2"
3.修改权限 chmod a+x run-as-cron.sh
Use:
./run-as-cron.sh
e.g.
./run-as-cron.sh /home/username/cron-env 'echo $PATH'
4.3crontab语法
* * * * * 命令
前面的五个*号,表示分、时、日、月、周,如:
代表意义 分钟 小时 日期 月份 周
数字范围 0-59 0-23 1-31 1-12 0-7
*号代表任何时间都接受的意思,任意。
*号之间用空格分开,如果是一段范围,用-号连接;如果是隔开几个时间,用,号表示。
另外,命令必须是编写计划任务的用户有权限执行的,并且最后用绝对路径。
5.开机启动
要把cron设为在开机的时候自动启动,在 /etc/rc.d/rc.local 脚本中加入 /sbin/service crond start 即可。
参考链接
Working with Excel Spreadsheets
How to Work With Excel Documents Using Python
Python: Get Today’s Current Date and Time
Importing a function from a class in another file?
Python2字符编码问题小结
Paython 2.7 manual
openpyxl manual
Openpyxl tutorial
openpyxl document
Execute python Script on Crontab
Setting the correct encoding when piping stdout in Python
How to enable crontab on Mac OS/X