Repository navigation
Expand file tree
/
Copy pathSearchExcel.py
More file actions
153 lines (130 loc) · 4.61 KB
/
Copy pathSearchExcel.py
File metadata and controls
153 lines (130 loc) · 4.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import os
import openpyxl
import xlrd
import datetime
import time
def change_datatype(row_data: list):
"""Excel单元格的内容类型检测和转换。
Args:
row_data (list): 行数据,列表格式
Returns:
list: 转换后的行数据
"""
result_data = []
for rd in row_data:
if type(rd) == datetime.datetime:
t = rd.strftime("%Y-%m-%d %H:%M:%S")
elif type(rd) == str:
t = rd
elif type(rd) == int:
t = str(rd)
elif type(rd) == float:
t = str(rd)
elif type(rd) is None:
t = ''
else:
t = str(rd)
result_data.append(t)
return result_data
def find_key(search_key: str, row_content: str):
"""检测关键词和内容。
Args:
search_key (str): 关键词
row_content (str): 行内容
Returns:
bool: 如果包含关键词返回True,否则返回False
"""
if search_key in row_content:
return True
else:
return False
def process_xls(path, file):
"""读取xls后缀的Excel文件。
Args:
path (str): 文件所在路径
file (str): 文件名
Yields:
tuple: 包含文件路径、工作表名、行数、行内容的元组
"""
filepath = os.path.join(path, file)
try:
rb = xlrd.open_workbook(filepath, formatting_info=True)
except:
return False
sheet_names = rb.sheet_names()
space_line = 0
for ws_name in sheet_names:
ws = rb.sheet_by_name(ws_name)
rows = ws.nrows
cols = ws.ncols
for r in range(rows):
values = [ws.cell(r, c).value for c in range(cols)]
values = change_datatype(values)
values = " ".join(values)
if values:
yield filepath, ws_name, r, values # 文件路径,工作表名,行数,行内容
else:
if space_line < 10:
space_line += 1
else:
break
def process_xlsx(path, file):
"""读取xlsx后缀的Excel文件。
Args:
path (str): 文件所在路径
file (str): 文件名
Yields:
tuple: 包含文件路径、工作表名、行数、行内容的元组
"""
filepath = os.path.join(path, file)
try:
wb = openpyxl.load_workbook(filepath, read_only=True, data_only=True)
except:
return False
worksheets_name = wb.sheetnames
space_line = 0
for ws_name in worksheets_name:
ws = wb[ws_name]
for index, row in enumerate(ws.rows):
values = [r.value for r in row if r.value != None]
values = change_datatype(values)
values = " ".join(values)
if values:
yield filepath, ws_name, index, values # 文件路径,工作表名,行数,行内容
else:
if space_line < 10:
space_line += 1
else:
break
def find_excel_data(search_key: str, target_dir: str):
"""检索指定目录下的Excel文件和过滤。
Args:
search_key (str): 检索的关键词
target_dir (str): 目标文件夹
Yields:
tuple: 包含文件路径、工作表名、行数、行内容的元组
"""
for path, dirs, files in os.walk(target_dir):
files = [file for file in files if not file.startswith('~$')] # 过滤掉正打开的excel文件
xls_files = [file for file in files if file.endswith('.xls')] # 取出所有的xls后缀文件
xlsx_files = [file for file in files if file.endswith('.xlsx')] # 取出所有的xlsx后缀文件
for xls in xls_files:
for data in process_xls(path, xls):
filepath, ws_name, index, values = data
status = find_key(search_key, values)
if status:
yield filepath, ws_name, index, values
for xlsx in xlsx_files:
for data in process_xlsx(path, xlsx):
filepath, ws_name, index, values = data
status = find_key(search_key, values)
if status:
yield filepath, ws_name, index, values # 输出内容:路径/文件名、工作表名、行数、行内容
if __name__ == '__main__':
time1 = time.time()
search_key = '刘家站垦殖场'
target_dir = './'
for data in find_excel_data(search_key, target_dir):
print(list(data))
time2 = time.time()
print("\n程序运行结束,停止运行。耗时:{}秒".format(round(time2 - time1, 2)))