#!/usr/bin/env python
##-*-coding=utf-8-*-
import xlrd
#打開excel文件
def open_excel(file= 'test.xls'):
try:
data = xlrd.open_workbook(file)
return data
except Exception,e:
print str(e)
#根據名稱獲取Excel表格中的數據 參數:file:Excel文件路徑 colnameindex:表頭列名所在行的索引 ,by_name:Sheet1名稱
# def excel_table_byname(file= 'test.xls', colnameindex=0):
# data = open_excel(file) #打開excel文件
# sheets = data.sheet_names()
# lenth = len(sheets)
# list = []
# all = []
# for i in range(lenth):
#
# table = data.sheet_by_index(i)
# cf = {}
# cf['name'] = table.name
# # table = data.sheet_by_name(by_name) #根據sheet名字來獲取excel中的sheet
# nrows = table.nrows #行數table.name
# # colnames = table.row_values(colnameindex) #某一行數據
# #裝讀取結果的序列`
#
# for row_num in range(0, nrows): #遍歷每一行的內容
# list = []
# row = table.row_values(row_num) #根據行號獲取行
# # if row: #如果行存在
# # app = [] #一行的內容
# # for i in range(len(colnames)): #一列列地讀取行的內容
# # app.append(row[i])
# # list.append(app) #裝載數據
# # cf['data'] = list
# if row:
# list.append(row)
# all.append(cf)
# return all
#主函數
def main():
tables = excel_table_byname('test.xls')
print tables
# dic = {}
# for table in tables:
# dic['name'] = table['name']
# for row in table['data']:
# dic['first'] = row[0]
# dic['two'] = row[1]
# # print dic
def excel_table_byname(file):
all_sheet = []
data = open_excel(file) # 打開excel文件
sheets = data.sheet_names()
lenth = len(sheets)
# 遍歷sheet
for i in range(lenth):
cf = {}
row_list = []
table = data.sheet_by_index(i)
cf['name'] = table.name
nrows = table.nrows
# 遍歷某一sheet的所有行
for row_num in range(nrows):
row = table.row_values(row_num)
row_list.append(row)
cf['data'] = row_list
all_sheet.append(cf)
return all_sheet
if __name__=="__main__":
main()
獲取excel表數據
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.