1
+ # -*- coding: utf-8 -*-
2
+
3
+ from openpyxl import load_workbook
4
+
5
+ class XlsxReader ():
6
+
7
+ def __init__ (self , filename ):
8
+ self ._wb = load_workbook (filename )
9
+
10
+ @property
11
+ def sheetnames (self ):
12
+ return self ._wb .sheetnames
13
+
14
+ def get_sheet_content (self , sheetname ):
15
+ return self ._wb [sheetname ]
16
+
17
+ def get_titles (self , sheetname ):
18
+ return [title .value for title in self .get_sheet_content (sheetname )["1" ]]
19
+
20
+ @property
21
+ def titles (self ):
22
+ '''迭代取'''
23
+ for sheetname in self .sheetnames :
24
+ yield {sheetname :self .get_titles (sheetname )}
25
+
26
+ @property
27
+ def titles_dict (self ):
28
+ '''全量字典'''
29
+ title_dict = dict ()
30
+ for y in self .titles :
31
+ title_dict = dict (title_dict , ** y )
32
+ return title_dict
33
+
34
+ def max_row (self , sheetname ):
35
+ return self .get_sheet_content (sheetname ).max_row
36
+
37
+ def max_column (self , sheetname ):
38
+ return self .get_sheet_content (sheetname ).max_column
39
+
40
+ def get_sheet_data (self , sheetname ):
41
+ '''获取某一张表的所有内容'''
42
+ for idx in range (2 , self .max_row (sheetname )+ 1 ):
43
+ yield [content .value for content in self .get_sheet_content (sheetname )[idx ]]
44
+
45
+ def get_sheet_contents (self , sheetname ):
46
+ '''获取某一张表的所有内容'''
47
+ sheet_data = self .get_sheet_data (sheetname )
48
+ for data in sheet_data :
49
+ if data [0 ] is not None :
50
+ yield {str (data [0 ]):data [1 :]}
51
+
52
+ def get_sheet_content_dict (self , sheetname ):
53
+ '''获取某一张表内容的全量字典'''
54
+ return [y for y in self .get_sheet_contents (sheetname )]
55
+
56
+ @property
57
+ def contents (self ):
58
+ '''全文件data'''
59
+ for sheetname in self .sheetnames :
60
+ yield {sheetname :self .get_sheet_content_dict (sheetname )}
61
+
62
+ @property
63
+ def contents_dict (self ):
64
+ return [y for y in self .contents ]
65
+
66
+ if __name__ == "__main__" :
67
+ x = XlsxReader ("./test.xlsx" )
68
+ print (x .sheetnames )
69
+ print (x .get_titles ("1" ))
70
+ print (x .titles_dict )
71
+ print (x .get_sheet_content_dict ("1" ))
72
+ print (x .contents_dict )
0 commit comments