利用python30以上的版本将excel表格拆分成若干个新表首先冻结窗格A1筛选第二行并找到姓名这一列按照姓名把所有想同姓名的行内容生成新的表格生成的新表格按照筛选的姓名命名并带有原表中冻结的窗格
A1。
下面是一个实现此功能的示例代码:
import openpyxl
# 打开原始表格
wb = openpyxl.load_workbook('原始表格.xlsx')
# 获取第一个工作表
sheet = wb.active
# 冻结窗格A1
sheet.freeze_panes = 'A2'
# 获取姓名列的列号
name_col = None
for cell in sheet[2]:
if cell.value == '姓名':
name_col = cell.column
break
# 如果找不到姓名列,则退出程序
if name_col is None:
print('找不到姓名列')
exit()
# 生成新表格
for row in sheet.iter_rows(min_row=2, values_only=True):
name = row[name_col - 1]
if name is None:
continue
name = name.strip()
if not name:
continue
if not isinstance(name, str):
name = str(name)
if not name:
continue
if not name.isprintable():
continue
if not name.isalnum():
continue
if not name[0].isalpha():
continue
if name[1:] and not name[1:].isdigit():
continue
ws = wb.create_sheet(name)
ws.freeze_panes = 'A2'
ws.append(sheet[1])
ws.append(row)
# 保存新表格
wb.save('拆分后的表格.xlsx')
以上代码首先打开原始表格,然后获取第一个工作表。接着冻结窗格A1,并找到姓名列的列号。如果找不到姓名列,则退出程序。
之后,程序遍历原表格中的每一行,如果该行的姓名列有值,则将该行复制到以该姓名命名的新表格中。如果该姓名的新表格不存在,则创建一个新表格并命名为该姓名。
最后,程序保存拆分后的新表格
原文地址: http://www.cveoy.top/t/topic/gpb3 著作权归作者所有。请勿转载和采集!