美文网首页
从excel中读取数据

从excel中读取数据

作者: 慧琴如翌 | 来源:发表于2018-03-23 15:48 被阅读24次
    
    class ExcelReader:
        """
        读取excel文件中的内容。返回list。
    
        如:
        excel中内容为:
        | A  | B  | C  |
        | A1 | B1 | C1 |
        | A2 | B2 | C2 |
    
        如果 print(ExcelReader(excel, title_line=True).data),输出结果:
        [{A: A1, B: B1, C:C1}, {A:A2, B:B2, C:C2}]
    
        如果 print(ExcelReader(excel, title_line=False).data),输出结果:
        [[A,B,C], [A1,B1,C1], [A2,B2,C2]]
    
        可以指定sheet,通过index或者name:
        ExcelReader(excel, sheet=2)
        ExcelReader(excel, sheet='BaiDuTest')
        """
        def __init__(self, excel, sheet=0, title_line=True):
            if os.path.exists(excel):
                self.excel = excel
            else:
                raise FileNotFoundError('文件不存在!')
            self.sheet = sheet
            self.title_line = title_line
            self._data = list()
    
        @property
        def data(self):
            if not self._data:
                workbook = open_workbook(self.excel)
                if type(self.sheet) not in [int, str]:
                    raise SheetTypeError('Please pass in <type int> or <type str>, not {0}'.format(type(self.sheet)))
                elif type(self.sheet) == int:
                    s = workbook.sheet_by_index(self.sheet)
                else:
                    s = workbook.sheet_by_name(self.sheet)
    
                if self.title_line:
                    title = s.row_values(0)  # 首行为title
                    for col in range(1, s.nrows):
                        # 依次遍历其余行,与首行组成dict,拼到self._data中
                        self._data.append(dict(zip(title, s.row_values(col))))
                else:
                    for col in range(0, s.nrows):
                        # 遍历所有行,拼到self._data中
                        self._data.append(s.row_values(col))
            return self._data
    
    
    if __name__ == '__main__':
        y = 'E:\Test_framework\config\config.yml'
        reader = YamlReader(y)
        print(reader.data)
    
        e = 'E:/Test_framework/data/baidu.xlsx'
        reader = ExcelReader(e, title_line=True)
        print(reader.data)
    

    转载自原文https://blog.csdn.net/huilan_same/article/details/76572466

    相关文章

      网友评论

          本文标题:从excel中读取数据

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