zoukankan      html  css  js  c++  java
  • 读取Excel数据封装

    """读取excel封装"""
    import xlrd
    import os
    
    class SheetTypeError(object):
        pass
    class ExcelReader(object):
        def __init__(self,excel_file,sheet_by):
            if os.path.exists(excel_file):
                self.excel_file = excel_file
                self.sheet_by = sheet_by
                self._data = list()
    
            else:
                raise FileNotFoundError("文件不存在")
    
        def data(self):
            #打开文件
            if not self._data:
                workbook = xlrd.open_workbook(self.excel_file)
                if type(self.sheet_by) not in [str,int]:
                    raise SheetTypeError("请输入Str , Int")
                elif type(self.sheet_by) == str:
                    sheet = workbook.sheet_by_name(self.sheet_by)
                elif type(self.sheet_by) == int:
                    sheet = workbook.sheet_by_index(self.sheet_by)
    
                #读取sheet内容
                #返回list,元素:字典
                #格式[{"a":"a1","b":"b1"},{"a":"a2","b":"b2"}]
                #1、获取首行的信息
                title = sheet.row_values(0)
                #2、遍历测试行,首行组成dict,放在list
                for row in range(1,sheet.nrows):
                    col_value = sheet.row_values(row)
                    self._data.append(dict(zip(title,col_value)))
    
            return self._data
    
    if __name__ == '__main__':
        test_data = ExcelReader("D:\20\Interface_Python\Params\test_data.xlsx",0)
        a=test_data.data()
        print(a)
    
  • 相关阅读:
    Some ArcGIS Tools
    Optimization Algorithms
    BPTT
    Markdown 简明语法
    【转载】softmax的log似然代价函数(求导过程)
    DP tricks and experiences
    Google Chrome Keyboard Shortcuts
    【转载】如何掌握所有的程序语言
    转 C++ 面向对象程序设计的基本特点
    leetcode 18. 4Sum
  • 原文地址:https://www.cnblogs.com/venvive/p/12902287.html
Copyright © 2011-2022 走看看