使用python对excel进行读写

工作周报或是日报,月报,是每一个IT民工的痛吧,一天忙碌下来还要被催着写周报…还好,我们的周报数据是
从项目管理平台(类似mantis)上导出来的。已经有前辈使用Perl写了将导出的excel数据进行筛选生成既定的
EXCEL格式的文档。

python-logo
大家都是懒人… 这个导出周报加上代码维护的工作交给了我。
我所要做的工作整个步骤是:登录网站(用户名/密码)->
->列表页面->输入条件->导出为||->使用Perl将导出文件进行处理->提交周报->…
如果将”导出为”之前的手工步骤也省略掉的话,那才真正实现一步完成..由于对Perl还不熟,所有步骤就选用python
重新写了!那就直接动手做吧:
分析:模块上包括登录WEB,下载文件,导出到EXCEL。
前两个模块都很简单,网上资料也很多:
1.登录,由于是登录后下载,所以需要模拟浏览器,使用cookies。这里就贴出测试的Demon

def get_srcfile(begindt,fridaydt):

    cj= cookielib.CookieJar()
    opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    opener.addheaders = [('User-agent','Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.1)')]
    params = urllib.urlencode({'username':'username',              
                           'password':'passwd',
                            'Cookies_Time': 1,
                             'IsLogin':True})
    #  with cookies
    login_page='http://www.xxx.com/login'
    login_data = urllib.urlencode({u"username":u'wangzhe2',u"password":u'wangzhe2'})   
    opener.open(login_page,login_data)
     ......
    opener.close()

2.下载文件:
减少文字量,参看这里吧:http://outofmemory.cn/code-snippet/83/sanzhong-Python-xiazai-url-save-file-code

3.读下载的文件,并导入生成的excel
这里不得不提到xlwt,xlrd,xlutils这几个包。
xlrd:读excel文件,从名字可以看出来,xls read 。地址:https://pypi.python.org/pypi/xlrd
xlwt:写excel文件,xls write,可以控制Excel中单元格的格式。地址:https://pypi.python.org/pypi/xlwt
xlutils:xlwt对于读取和生成Excel文件都非常容易处理,但是对于已经存在的Excel文件进行修改就存在问题了,
xlutils(依赖于xlrd和xlwt)提供复制excel文件内容和修改文件的功能。
下载地址:https://pypi.python.org/pypi/xlutils
具体参见文档: http://www.python-excel.org/   http://pythonhosted.org/xlutils/

不得不说在使用的时候遇到了问题,我需要的是操作office 2007+ 的xlsx文件,而且要用到excel的数据验证和下拉选框
(Data validation and drop down lists),这样问题显而易见了,这个包肯定不能用了。
于是,必须要重新选择其他方法了,这时Google给出了这个最佳答案: XlsxWriter!
  https://pypi.python.org/pypi/XlsxWriter
通过介绍可以看得出来,XlsxWriter可以操作xlsx文件,单元格写入文本,数字,公式,日期等不同格式;格式化表格,
图表,合并单元格等等。,最主要满足Data validation and drop down lists操作的需求。

excel 数据验证 xlsxWriter
excel 数据验证 xlsxWriter

XlsxWriter is a Python module for creating Excel XLSX files.
XlsxWriter supports the following features:

100% compatible Excel XLSX files.
Write text, numbers, formulas, dates to cells.
Write hyperlinks to cells.
Full cell formatting.
Multiple worksheets.
Charts.
Page setup methods for printing.
Merged cells.
Defined names.
Autofilters.
Data validation and drop down lists.
Conditional formatting.
Worksheet PNG/JPEG images.
Rich multi-format strings.
Cell comments.
Document properties.
Worksheet cell protection.
Freeze and split worksheet panes.
Worksheet Tables.
Sparklines.
Outlines and Grouping.
Memory optimisation mode for writing large files.
Standard libraries only.
Python 2.6, 2.7, 3.1, 3.2 and 3.3 support.

You may also like