python中使用xlrd、xlwt读写excel(xls格式)

在工作中我们常常要将excel中的数据进行读写,用python对excel读写非常容易,我们只需要下载安装python提供的xlrd和xlwt库即可方便编程实现excel的读写。

1.下载:
xlrd下载地址:https://pypi.python.org/pypi/xlrd
xlwt下载地址:https://pypi.python.org/pypi/xlwt

2.安装:(以xlrd为例)
linux:

$ tar xzf xlrd.tgz  
$ cd xlrd-0.7.1  
$ python setup.py install  

windows:

C:\> cd xlrd-0.7.1 
根据安装的python确定目录,这里我安装的2.7版本,故写为: 
C:\xlrd-0.7.1> \Python27\python setup.py install  

3.xlrd读excel

import xlrd

fname = "B:/1.xls"
data = xlrd.open_workbook(fname)
shxrange = range(data.nsheets)
try:
    sh = data.sheet_by_name("Sheet1")
except:
    print "no sheet in %s named Sheet1" % fname
nrows = sh.nrows
ncols = sh.ncols
print "nrows %d, ncols %d" % (nrows,ncols)

for row_index in range(sh.nrows):
    for col_index in range(sh.ncols):
        #all cell#
        print sh.cell(row_index,col_index).value

4.xlwt写excel

import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')
# indexing is zero based, row then column
sheet.write(0,0,'test text')
sheet.write(1,1,'test text')
sheet.write(2,2,'test text')
sheet.write(3,3,'test text')
sheet.write(4,4,'test text')
sheet.write(5,5,'test text')
wbk.save('B:/test3.xls')

参考链接:
http://www.jb51.net/article/60510.htm
http://huaxia524151.iteye.com/blog/1173828
http://blog.sina.com.cn/s/blog_5357c0af01019gjo.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值