查看: 145|回复: 1

openpyxl批量格式化Excel报表:标题蓝底加粗、边框、自动列宽与冻结首行

[复制链接]
发表于 2 小时前 | 显示全部楼层 |阅读模式
公司要求所有报表统一格式:标题行加粗、蓝色背景、字号12、单元格加边框。每次导出数据都是裸表,手动调整50份表格至少4小时。用Python+openpyxl只需10秒。

技术原理
pandas擅长数据处理不擅长格式控制,openpyxl直接操作Excel格式属性。核心对象:Font(字体)、PatternFill(填充)、Border(边框)、Alignment(对齐)、column_dimensions(列宽)、freeze_panes(冻结行)。工作流程:加载.xlsx → 应用格式 → 保存。

环境准备
pip install openpyxl

完整代码
  1. import os
  2. from openpyxl import load_workbook
  3. from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
  4. def format_excel_sheet(input_file, output_file=None):
  5.     if output_file is None:
  6.         base_name = os.path.splitext(input_file)[0]
  7.         output_file = f"{base_name}_已格式化.xlsx"
  8.     wb = load_workbook(input_file)
  9.     ws = wb.active
  10.     # 定义样式
  11.     title_font = Font(name='微软雅黑', size=12, bold=True, color='FFFFFF')
  12.     title_fill = PatternFill(start_color='4472C4', fill_type='solid')
  13.     data_font = Font(name='微软雅黑', size=11)
  14.     thin_border = Border(
  15.         left=Side(style='thin'),
  16.         right=Side(style='thin'),
  17.         top=Side(style='thin'),
  18.         bottom=Side(style='thin')
  19.     )
  20.     center_align = Alignment(horizontal='center', vertical='center')
  21.     left_align = Alignment(horizontal='left', vertical='center')
  22.     max_row = ws.max_row
  23.     max_col = ws.max_column
  24.     if max_row < 1:
  25.         print(f"警告: {input_file} 没有数据")
  26.         return
  27.     # 格式化标题行
  28.     for col in range(1, max_col + 1):
  29.         cell = ws.cell(row=1, column=col)
  30.         cell.font = title_font
  31.         cell.fill = title_fill
  32.         cell.border = thin_border
  33.         cell.alignment = center_align
  34.     # 格式化数据行
  35.     for row in range(2, max_row + 1):
  36.         for col in range(1, max_col + 1):
  37.             cell = ws.cell(row=row, column=col)
  38.             cell.font = data_font
  39.             cell.border = thin_border
  40.             if isinstance(cell.value, (int, float)):
  41.                 cell.alignment = center_align
  42.             else:
  43.                 cell.alignment = left_align
  44.     # 自动列宽
  45.     for col in range(1, max_col + 1):
  46.         max_length = 0
  47.         column_letter = ws.cell(row=1, column=col).column_letter
  48.         for row in range(1, max_row + 1):
  49.             cell_value = ws.cell(row=row, column=col).value
  50.             if cell_value:
  51.                 cell_length = len(str(cell_value))
  52.                 if cell_length > max_length:
  53.                     max_length = cell_length
  54.         adjusted_width = min(max(max_length + 2, 10), 30)
  55.         ws.column_dimensions[column_letter].width = adjusted_width
  56.     # 冻结首行
  57.     ws.freeze_panes = 'A2'
  58.     wb.save(output_file)
  59.     print(f"格式化完成: {output_file}")
  60. def batch_format_excel_files(folder_path):
  61.     count = 0
  62.     for filename in os.listdir(folder_path):
  63.         if filename.endswith('.xlsx') and '已格式化' not in filename:
  64.             file_path = os.path.join(folder_path, filename)
  65.             format_excel_sheet(file_path)
  66.             count += 1
  67.     print(f"\n批量格式化完成!共处理 {count} 个文件")
  68. if __name__ == "__main__":
  69.     # 单个文件: format_excel_sheet("原始数据.xlsx")
  70.     batch_format_excel_files(r"D:\待格式化报表")
复制代码

代码逐行解析

样式对象定义
Font参数:name(字体名,如微软雅黑、Arial)、size(字号)、bold(加粗True/False)、italic(斜体)、color(HEX颜色码,如FFFFFF白色)。

背景色填充
PatternFill(start_color='4472C4', fill_type='solid'),其中start_color为HEX色值,fill_type='solid'表示纯色。常用颜色:4472C4(Office蓝)、C00000(红)、70AD47(绿)、FFC000(橙)、E2EFDA(浅绿)。

边框设置
Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin')),Side的style可选thin、medium、thick、double、dashed、dotted。

自动列宽计算
adjusted_width = min(max(max_length + 2, 10), 30):最大值加2余量,最小10,最大30防止超长文本撑爆列。

冻结首行
ws.freeze_panes = 'A2':滚动数据时标题行始终保持可见。

进阶技巧

条件格式:自动高亮异常值
  1. from openpyxl.formatting.rule import CellIsRule
  2. ws.conditional_formatting.add(
  3.     f'B2:B{max_row}',
  4.     CellIsRule(
  5.         operator='lessThan',
  6.         formula=['0'],
  7.         fill=PatternFill(start_color='FFC7CE', fill_type='solid')
  8.     )
  9. )
复制代码
高亮所有小于0的数值(红色背景)。

隔行变色(斑马纹)
  1. light_fill = PatternFill(start_color='F2F2F2', fill_type='solid')
  2. for row in range(2, max_row + 1):
  3.     if row % 2 == 0:
  4.         for col in range(1, max_col + 1):
  5.             ws.cell(row=row, column=col).fill = light_fill
复制代码
偶数行填充浅灰色增强可读性。

从模板复制格式
  1. import shutil
  2. shutil.copy("公司标准模板.xlsx", output_file)
  3. wb = load_workbook(output_file)
  4. ws = wb.active
  5. for row_idx, row_data in enumerate(data_rows, start=2):
  6.     for col_idx, value in enumerate(row_data, start=1):
  7.         ws.cell(row=row_idx, column=col_idx, value=value)
复制代码
先复制带格式的空白模板,再填入数据。

常见问题

Q1:保存时报错ValueError: Max value is 255
原因:openpyxl对旧版.xls格式支持有限。解决:确保文件是.xlsx格式,若为.xls则用Excel另存为.xlsx。

Q2:中文显示为方框(乱码)
原因:系统缺少指定字体。改用通用字体如 'Arial Unicode MS' 或 'SimSun'(宋体)。

Q3:如何设置行高?
  1. # 单独设置第一行
  2. ws.row_dimensions[1].height = 25
  3. # 批量设置所有行
  4. for row in range(1, max_row + 1):
  5.     ws.row_dimensions[row].height = 20
复制代码

总结
格式需求与openpyxl对应:字体->Font(name,size,bold,color);背景色->PatternFill(start_color,fill_type);边框->Border(Side(style));对齐->Alignment(horizontal,vertical);列宽->column_dimensions[].width;行高->row_dimensions[].height;冻结窗格->freeze_panes='A2'。
通过脚本自动化控制Excel格式,配合批量处理函数可快速完成大量报表格式化任务。
回复

使用道具 举报

发表于 1 小时前 | 显示全部楼层

Re: openpyxl批量格式化Excel报表:标题蓝底加粗、边框、自动列宽与冻结首行

这个脚本很实用,解决了手工调格式的痛点。标题蓝底加粗、边框、自动列宽、冻结首行这些常规格式化需求都覆盖了,代码结构也清晰,直接就可以拿过来改路径用。 有个小建议:如果报表里存在合并单元格,目前代码按行遍历可能会报错或漏改,可以考虑加个异常处理或者用 `merged_cells.ranges` 检查一下。另外,是否需要支持多工作表(比如循环所有 `ws`)或者处理 `.xls` 旧格式?不过针对公司固定格式的 `.xlsx` 任务,这套逻辑已经足够高效了。 感谢分享,准备存下来下次批量出报表时试试。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

指导单位

江苏省公安厅

江苏省通信管理局

浙江省台州刑侦支队

DEFCON GROUP 86025

Hacking Group 021A

旗下站点

态势感知中心

应急响应中心

红盟安全

联系我们

官方QQ群:112851260

官方邮箱:security#ihonker.org(#改成@)

官方核心成员

关注微信公众号

Archiver|手机版|小黑屋| ( 沪ICP备2021026908号 )

GMT+8, 2026-6-22 12:23 , Processed in 0.028941 second(s), 18 queries , Gzip On, Redis On.

Powered by ihonker.com

Copyright © 2015-现在.

  • 返回顶部