python-读取excel文件
# -*- coding:utf-8 -*-
__author__ = 'zzd'
import xlrd
#open excelfile
def open_excel(file):
try:
data = xlrd.open_workbook(file)
return data
except Exception,e:
print(str(e))
#根据名称获取Excel表格中的数据 参数:file:Excel文件路径 by_name:Sheet1名称
def excel_table_byname(data,by_name):
# table = data.sheet_by_name(unicode(by_name, "utf-8"))
table = data.sheet_by_name(by_name.encode('gbk'))
nrows = table.nrows #行数
ncols = table.ncols # 列数
list =[[] for i in range(nrows)]
for i in range(0,nrows):
for j in range(0,ncols):
cell = table.cell(i,j).value
if(cell!=""):
list[i].append(cell)
return list
# get table's index info from sheet 1
def getTbInfo(data):
dataList = excel_table_byname(data,"Sheet1")
for i in range(len(dataList[0])):
if(dataList[0][i]==u'表名'):
index=i
# print index
tbinfos={}
#i代表表格的行,j代表表格的列
for i in range(2,len(dataList)):
tbinfo={}
tbname=dataList[i][index]
# print len(dataList[i])
for j in range(len(dataList[0])):
key=dataList[0][j].strip()
if(j<len(dataList[i])):
value=dataList[i][j]
else:
value=""
tbinfo[key]=value
tbinfos[tbname]=tbinfo
return tbinfos
ฅ平平庸庸的普通人ฅ