import xdrlib, sys
import xlrd
#open the excel file
def open_excel(file= '111.xls'):
try:
data = xlrd.open_workbook(file)
return data
except Exception,e:
print str(e)
# get the excel by index
def excel_table_byindex(file= '111.xls',colnameindex=0,by_index=0):
data = open_excel(file)
table = data.sheets()[by_index] # we get sheet1 in excel as 'table'
nrows = table.nrows # get number of rows, here nrows = 5
ncols = table.ncols # get number of cols, here ncols = 2
#print nrows, ncols
colnames = table.row_values(colnameindex) # get the name of each col, here is [airport, standard]
#print colnames
list = [] # a blank list to store
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)
#print list
return list
def excel_table_byname(file = '111.xls', 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()
Python读取excel的基本方法-源代码
最新推荐文章于 2024-08-14 14:43:08 发布