python 读取Excel文件

#导包
import xlrd
file= u'D:\\test\\学信网zh.xlsx'
xlrd.open_workbook(file)
们在解析Excel 表格时 ,主要利用的是一个类似二维数组的方式,一般的Excel表格,第一行一般是表头,
,如果你的没有表头那就解析起来更加简单。我们以有表头的为例:

#-*- coding=utf-8 -*-
import xlrd
def open_excel(file= 'file.xls'):
    try:
        data = xlrd.open_workbook(file)
        return data
    except Exception as e:
        print(str(e))

def excel_table_byname(file= u'D:\\test\\学信网zh.xlsx',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): #也就是从Excel第二行开始,第一行表头不算
         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_byname()
    for row in tables:
       print(row)
if __name__ =="__main__":
    main()

猜你喜欢

转载自blog.csdn.net/xiuxiu179/article/details/80136307