import osimport openpyxldef extract_subtables(folder_path): subtables = [] for filename in os.listdir(folder_path): if filename.startswith('2-') and filename.endswith('.xlsx'): file_path = os.path.join(folder_path, filename) workbook = openpyxl.load_workbook(file_path) for sheet_name in workbook.sheetnames: if sheet_name.startswith('2-'): sheet = workbook[sheet_name] subtable = [] for row in sheet.iter_rows(min_row=2): if not all([cell.value is None for cell in row]): subtable.append([cell.value for cell in row]) elif subtable: subtables.append(subtable) subtable = [] if subtable: subtables.append(subtable) return subtables,给出完整代码
时间: 2024-02-14 16:05:06 浏览: 66
好的,下面是完整代码。
```python
import os
import openpyxl
def extract_subtables(folder_path):
subtables = []
for filename in os.listdir(folder_path):
if filename.startswith('2-') and filename.endswith('.xlsx'):
file_path = os.path.join(folder_path, filename)
workbook = openpyxl.load_workbook(file_path)
for sheet_name in workbook.sheetnames:
if sheet_name.startswith('2-'):
sheet = workbook[sheet_name]
subtable = []
for row in sheet.iter_rows(min_row=2):
if not all([cell.value is None for cell in row]):
subtable.append([cell.value for cell in row])
elif subtable:
subtables.append(subtable)
subtable = []
if subtable:
subtables.append(subtable)
return subtables
if __name__ == '__main__':
folder_path = 'path/to/your/folder'
subtables = extract_subtables(folder_path)
for subtable in subtables:
print(subtable)
```
你只需要将`path/to/your/folder`替换成你要处理的文件夹路径即可。在运行代码后,会打印出所有提取出的子表。如果你要将子表保存到文件中,可以使用`openpyxl`库提供的写入Excel文件的方法。
阅读全文