一、安装xlrd模块
到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境。
二、使用介绍
1、导入模块
import xlrd
2、打开Excel文件读取数据
data = xlrd.open_workbook('excelFile.xls')
3、使用技巧
获取一个工作表
import xdrlib, sys
import xlrd
def open_excel(file='file.xlsx'):
try:
data = xlrd.open_workbook(file)
return data
except Exception, e:
print str(e)
def excel_table_byindex(file='file.xlsx', colnameindex=0, by_index=0):
data = open_excel(file)
table = data.sheets()[by_index]
nrows = table.nrows
ncols = table.ncols
colnames = table.row_values(colnameindex)
list = []
for rownum in range(1, nrows):
row = table.row_values(rownum)
if row:
app = {}
for i in range(len(colnames)):
app[colnames[i]] = row[i]
list.append(app)
return list
def excel_table_byname(file='file.xlsx',colnameindex=0, by_name=u'Sheet1'):
data = open_excel(file)
table = data.sheet_by_name(by_name)
nrows = table.nrows
colnames = table.row_values(colnameindex)
list = []
for rownum in range(1, nrows):
row = table.row_values(rownum)
if row:
app = {}
for i in range(len(colnames)):
app[colnames[i]] = row[i]
list.append(app)
return list
def main():
tables = excel_table_byindex()
for row in tables:
print row
tables = excel_table_byname()
for row in tables:
print row
if __name__ == "__main__" :
main()