Python 使用 openpyxl 库拆分 Excel 表格并带原格式保存
以下是实现上述功能的 Python 代码:
import os
import openpyxl
# 打开原始 Excel 文件
wb = openpyxl.load_workbook('原始文件.xlsx')
# 获取第一个工作表
ws1 = wb.active
# 冻结第一个工作表窗格 A1 行的内容
ws1.freeze_panes = 'A2'
# 获取名字为表头的列
header_col = 'A'
for cell in ws1[1]:
if cell.value == '表头':
header_col = cell.column_letter
break
# 创建文件夹并保存到桌面
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
folder_path = os.path.join(desktop_path, "拆分文件夹")
os.makedirs(folder_path, exist_ok=True)
# 遍历表头列中所有相同内容的行,生成新的工作表
for row in ws1.iter_rows(min_row=2):
header_value = row[header_col + '1'].value
new_wb = openpyxl.Workbook()
new_ws = new_wb.active
# 把窗格 A1 的内容写入到新的工作表
new_ws['A1'].value = ws1['A1'].value
new_ws['A1'].font = ws1['A1'].font
new_ws['A1'].fill = ws1['A1'].fill
new_ws['A1'].border = ws1['A1'].border
new_ws['A1'].alignment = ws1['A1'].alignment
# 把表头列中所有相同内容的行带原格式复制到新的工作表
for cell in row:
new_ws[cell.coordinate].value = cell.value
new_ws[cell.coordinate].font = cell.font
new_ws[cell.coordinate].fill = cell.fill
new_ws[cell.coordinate].border = cell.border
new_ws[cell.coordinate].alignment = cell.alignment
# 把新的工作表保存为单独的 Excel 文件并以表头列中的内容命名
filename = header_value + '.xlsx'
filepath = os.path.join(folder_path, filename)
new_wb.save(filepath)
# 关闭原始 Excel 文件
wb.close()
需要注意的是,上述代码中的原始文件.xlsx、表头和A等参数需要根据实际情况进行修改。此外,代码中还使用了os库来创建文件夹并保存文件,因此需要确保电脑上已经安装了该库。
原文地址: https://www.cveoy.top/t/topic/fW8m 著作权归作者所有。请勿转载和采集!