美文网首页
python读取excel数据

python读取excel数据

作者: summer琴 | 来源:发表于2020-05-21 12:01 被阅读0次

依赖第三方库

xlrd

pip install xlrd

代码

# coding: utf-8
# author: liuqin
import xlrd
class ExcelUtil():
    def __init__(self, excelname, sheetname):
        self.wb = xlrd.open_workbook(excelname)
        self.data = self.wb.sheet_by_name(sheetname)
        '''获取第一行数据,即表头'''
        self.keys = self.data.row_values(0)
        '''获取总行数'''
        self.rowsNum = self.data.nrows
        '''获取总列数'''
        self.colsNum = self.data.ncols
    def dict_data(self):
        if self.rowsNum <= 1:
            print("没有数据")
        else:
            '''定义一个列表存放所有数据'''
            r = []
            j = 1
            '''这里要把第一行表头去掉,所以从第二行开始循环'''
            for i in range(1,self.rowsNum):
                '''定义一个字典来存放每一行的数据'''
                s = {}
                '''row_data返回第i行的数据'''
                row_data = self.data.row_values(i)
                '''列循环'''
                for j in range(0,self.colsNum):
                    s[self.keys[j]] = row_data[j]
                r.append(s)
        return r
excel = ExcelUtil('test.xlsx', 'test_data')
print("rows: " + str(excel.rowsNum))
print("cols: " + str(excel.colsNum))
print(excel.dict_data())
#print(excel.keys)



测试数据:
excel文件可以按照自己的需求指定path,这里是放在代码同级目录下,所以没有加具体路径


image.png

动动手试一下吧!

相关文章

网友评论

      本文标题:python读取excel数据

      本文链接:https://www.haomeiwen.com/subject/fqdzohtx.html