python操作excel,将每行信息放在字典里,所有信息放在一个列表里

#coding=utf8
from selenium import webdriver
import xlrd,os



dirname = os.path.dirname(os.path.dirname(__file__))
#join时,第二参数首位不能加/
filename = os.path.join(dirname,r'testdata/select_school.xlsx')

#row,col获取哪行那列的值
def run_select_shool(row=1,col=1):
    #打开excel文件读取数据
    data = xlrd.open_workbook(filename)
    table = data.sheet_by_index(0)

    row = row-1
    col = col-1
    #获取整行整列的值
    nrows = table.row_values(row)
    ncols = table.col_values(0)
    print(nrows[col])

def run_select_school2(filename,sheet_index=0,table_header_row=0):
    # 打开excel文件读取数据
    data = xlrd.open_workbook(filename)
    table = data.sheet_by_index(sheet_index)
    nrows = table.nrows
    nclos = table.ncols

    #获取表头行的信息
    header_row_data = table.row_values(table_header_row)
    #将每行的信息放入一个字典,再将字典放入一个列表中
    list = []
    for rownum in range(1,nrows):
        rowdata = table.row_values(rownum)
        #如果rowdata有值,
        if rowdata:
            dict = {}
            for j in range(0,len(header_row_data)):
                dict[header_row_data[j]] = rowdata[j]
            list.append(dict)
    print(list)
    return list



run_select_school2(filename)



猜你喜欢

转载自blog.csdn.net/qq_35958094/article/details/80166418