您的位置:首页 > 编程语言 > Python开发

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

2015-10-19 11:31 751 查看
在工作中我们常常要将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')


参考链接:

/article/1279408.html

/article/4035834.html

http://blog.sina.com.cn/s/blog_5357c0af01019gjo.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: