Repository navigation
Expand file tree
/
Copy pathSplitExcel.py
More file actions
140 lines (116 loc) · 4.87 KB
/
Copy pathSplitExcel.py
File metadata and controls
140 lines (116 loc) · 4.87 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
import os
import xlrd, xlwt
import openpyxl
import datetime
def generate_xls(filepath: str, worksheet_data: dict) -> str:
"""生成新的xls文件。
Args:
filepath (str): 原始文件路径
worksheet_data (dict): 工作表数据字典
Returns:
str: 新生成的文件路径
"""
datetime_str = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')
new_filepath = filepath.replace('.xls', '_Split_{}.xls'.format(datetime_str))
new_workbook = xlwt.Workbook(encoding='utf-8')
for worksheet_name, row_data_list in worksheet_data.items():
new_worksheet = new_workbook.add_sheet(worksheet_name)
for row_index, row_data in enumerate(row_data_list):
for column_index, data in enumerate(row_data):
new_worksheet.write(row_index, column_index, data)
new_workbook.save(new_filepath)
return new_filepath
def process_xls(filepath: str, column: int, worksheet_name: str = None) -> str:
"""处理xls格式的Excel文件。
Args:
filepath (str): Excel文件路径
column (int): 要拆分的列号
worksheet_name (str, optional): 工作表名称,默认为第一个工作表
Returns:
str: 处理结果信息
"""
try:
workbook = xlrd.open_workbook(filepath, formatting_info=True)
except:
return "文件读取异常:{}".format(filepath)
if worksheet_name:
worksheet = workbook.sheet_by_name(worksheet_name)
else:
worksheet = workbook.sheet_by_index(0)
rows = worksheet.nrows
cols = worksheet.ncols
split_data_dict = {}
for r in range(rows):
row_data = [worksheet.cell(r, c).value if worksheet.cell(r, c).value else ' ' for c in range(cols)]
temp_data = row_data[column - 1]
temp_data_list = split_data_dict.get(temp_data, [])
temp_data_list.append(row_data)
split_data_dict[temp_data] = temp_data_list
new_filepath = generate_xls(filepath, split_data_dict)
return "数据保存在新文件中,文件名:{}".format(new_filepath)
def generate_xlsx(filepath: str, worksheet_data: dict) -> str:
"""生成新的xlsx文件。
Args:
filepath (str): 原始文件路径
worksheet_data (dict): 工作表数据字典
Returns:
str: 新生成的文件路径
"""
datetime_str = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')
new_filepath = filepath.replace('.xlsx', '_Split_{}.xlsx'.format(datetime_str))
new_workbook = openpyxl.Workbook()
for worksheet_name, row_data_list in worksheet_data.items():
new_worksheet = new_workbook.create_sheet(worksheet_name)
for row_data in row_data_list:
new_worksheet.append(row_data)
new_workbook.save(new_filepath)
return new_filepath
def process_xlsx(filepath: str, column: int, worksheet_name: str = None) -> str:
"""处理xlsx格式的Excel文件。
Args:
filepath (str): Excel文件路径
column (int): 要拆分的列号
worksheet_name (str, optional): 工作表名称,默认为活动工作表
Returns:
str: 处理结果信息
"""
try:
workbook = openpyxl.load_workbook(filepath, read_only=True, data_only=True)
except:
return "文件读取异常:{}".format(filepath)
if worksheet_name:
worksheet = workbook.get_sheet_by_name(worksheet_name)
else:
worksheet = workbook.active
if worksheet.max_column < column:
return "最大列数是{},取不到第{}列".format(worksheet.max_column, column)
split_data_dict = {}
for row in worksheet.rows:
row_data = [cell.value if cell.value else ' ' for cell in row]
temp_data = row_data[column - 1]
temp_data_list = split_data_dict.get(temp_data, [])
temp_data_list.append(row_data)
split_data_dict[temp_data] = temp_data_list
new_filepath = generate_xlsx(filepath, split_data_dict)
return "数据保存在新文件中,文件名:{}".format(new_filepath)
def split_excel(filepath: str, column: int, worksheet_name: str = None) -> str:
"""拆分Excel文件根据指定列。
Args:
filepath (str): Excel文件路径
column (int): 要拆分的列号
worksheet_name (str, optional): 工作表名称
Returns:
str: 处理结果信息
"""
if filepath.endswith('.xlsx'):
result = process_xlsx(filepath, column, worksheet_name)
elif filepath.endswith('.xls'):
result = process_xls(filepath, column, worksheet_name)
else:
return "文件格式不对,不进行处理"
return result
if __name__ == "__main__":
filename = 'sedemo.xls'
# filename = 'SEdemo.xlsx'
result = split_excel(filename, 6) # 处理文件,表格的第六列,worksheet_name指定工作表,不指定则读取文件默认工作表
print(result)