利用python38版本openpyxl库拆分表格首先获取第一个工作表然后冻结第一个工作表窗格A1行的内容之后从第二行开始获取名字为表头的列将获取的列中所有相同内容的行带原格式生成一个新的工作表并带原格式把窗格A1的内容写入到每一个新的工作表新的工作表生成单独的excel文件并以表头列中的内容命名新建一个文件夹保存到桌面中代码怎么写
以下是利用python3.8版本openpyxl库拆分表格的代码:
import os
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection
from openpyxl.worksheet.page import PageMargins
# 设置工作表列宽
def set_column_width(ws):
for column in ws.columns:
max_length = 0
column = list(column)
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length + 2) * 1.2
ws.column_dimensions[get_column_letter(column[0].column)].width = adjusted_width
# 设置工作表样式
def set_cell_style(cell):
# 设置填充颜色
fill = PatternFill("solid", fgColor="FFFF00")
cell.fill = fill
# 设置边框
border = Border(left=Side(border_style="thin", color="000000"),
right=Side(border_style="thin", color="000000"),
top=Side(border_style="thin", color="000000"),
bottom=Side(border_style="thin", color="000000"))
cell.border = border
# 设置对齐方式
cell.alignment = Alignment(horizontal="center", vertical="center")
# 设置保护方式
cell.protection = Protection(locked=True)
# 获取表格数据
def get_table_data(file_path):
wb = openpyxl.load_workbook(file_path)
ws = wb.active
# 冻结窗格
ws.freeze_panes = 'A2'
# 获取表头列
header = {}
for cell in ws[1]:
header[cell.value] = cell.column_letter
# 按表头列生成新的工作表
for key in header:
new_wb = openpyxl.Workbook()
new_ws = new_wb.active
new_ws.title = key
# 写入窗格A1的内容
new_ws['A1'].value = ws['A1'].value
set_cell_style(new_ws['A1'])
# 获取相同内容的行
for row in ws.iter_rows(min_row=2):
if row[header[key]-1].value:
if not os.path.exists('output'):
os.mkdir('output')
if not os.path.exists('output/'+key):
os.mkdir('output/'+key)
new_file_path = 'output/'+key+'/'+row[header[key]-1].value+'.xlsx'
if os.path.exists(new_file_path):
new_wb = openpyxl.load_workbook(new_file_path)
new_ws = new_wb.active
else:
new_ws = new_wb.create_sheet(title=row[header[key]-1].value)
set_column_width(new_ws)
new_ws.sheet_properties.pageSetUpPr.fitToPage = True
new_ws.page_margins = PageMargins(left=0.5, right=0.5, top=0.5, bottom=0.5, header=0.5, footer=0.5)
# 写入窗格A1的内容
new_ws['A1'].value = ws['A1'].value
set_cell_style(new_ws['A1'])
# 写入行数据
for i in range(len(row)):
new_ws.cell(row=new_ws.max_row+1, column=i+1, value=row[i].value)
set_column_width(new_ws)
# 保存新的工作表
new_wb.save(new_file_path)
if __name__ == '__main__':
get_table_data('data.xlsx')
这段代码会在桌面上新建一个名为“output”的文件夹,然后在该文件夹中按表头列生成新的工作表,并将相同内容的行带原格式写入到每个新的工作表中。新的工作表会生成单独的excel文件,并以表头列中的内容命名。同时,窗格A1的内容也会带原格式写入到每个新的工作表中
原文地址: http://www.cveoy.top/t/topic/gqGN 著作权归作者所有。请勿转载和采集!