项目中要用到这个,所以记录一下。
python下读取excel文件方法多种,用的是普通的xlrd插件,因为它各种版本的excel文件都可读。
首先在https://pypi.python.org/pypi/xlrd下载插件安装,命令是“python setup.py install”,然后直接import xlrd就可以了。
下面是找到的现成函数,一个是按表的索引读,一个是按表名读,其实都一样啦。
import xlrd def open_excel(filename= 'file.xls'):
try:
data = xlrd.open_workbook(filename)
return data
except Exception,e:
print str(e) def excel_table_byindex(filename= 'file.xls',colnameindex=0,by_index=0):
data = open_excel(filename)
table = data.sheets()[by_index]
nrows = table.nrows
#ncols = table.ncols
colnames = table.row_values(colnameindex)
datalist =[]
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]
datalist.append(app)
return datalist def excel_table_byname(filename= 'file.xls',colnameindex=0,by_name=u'Sheet1'):
data = open_excel(filename)
table = data.sheet_by_name(by_name)
nrows = table.nrows
colnames = table.row_values(colnameindex)
datalist =[]
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]
datalist.append(app)
return datalist def test():
tables = excel_table_byindex()
for row in tables:
print row