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

使用python读取xls文件

2014-07-21 22:09 417 查看
配置文件越来越多,人工运营容易出错,根据一些规则来进行检测就比较有需要了,这个时候使用python就能比较快的进行对应的检查,这里简单介绍一些如何使用python来读取xls文件。

老规矩,先来一段代码:

# -*- coding:utf-8 -*-
import xlrd

def main():
xlsFile = xlrd.open_workbook("test.xls")
sheets = xlsFile.sheet_names()
print "xls has %d sheets" % xlsFile.nsheets
for sheetName in sheets:
printSheet(xlsFile, sheetName)

def printSheet(oXls, sheetName):
sheetIsEmpty = True
tmpSheet = oXls.sheet_by_name(sheetName)
tmpLine = ""

for row in range(tmpSheet.nrows):
for col in range(tmpSheet.ncols):
if tmpSheet.cell(row, col).value != None:
sheetIsEmpty = False
try:
tmpLine += str(tmpSheet.cell(row, col).value) + "\t"
except:
tmpLine += tmpSheet.cell(row, col).value + "\t"
tmpLine += "\n"

if sheetIsEmpty == False:
print "sheet name:%s" % sheetName
print tmpLine

if __name__ == "__main__":
main()


还是没有注释哈。。。这里说明一下过程。

安装xlrd:

1.xlrd不是python的标准库,需要下载,下载地址为:https://pypi.python.org/pypi/xlrd 需要说明的是针对python2.x和python3.x的库是不同的。

2.下载解压后,在目录下执行python setup.py install,我是在win7下执行的,linux下应该也没问题,macos上没试。

3.安装后,import xlrd,如果不报错就证明可用了。

xlrd的使用:

1.打开文件,直接用open_workbook,参数为对应的xls文件的路径。

2.获取xls的各个sheet页,可以使用sheet_names()或者直接用nsheets来获取index的个数

3.如果使用sheet_names()方法,那么后续读取sheet页就是使用sheet_by_name()方法,如果是使用的index方法,那么就使用sheet_by_index()方法

4.每个sheet的行列数直接使用成员nrows和ncols来获取范围

5.每个cell使用cell(row,col).value来获取值

拿到值之后想怎么处理就怎么处理了,这就是后话了。

更多参考请见官方主页:https://pythonhosted.org/xlrd3/general.html#

貌似3.x和2.x的api是一样的。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: