我的知识记录

Python Excel添加边框样式:细线粗线内外框一键设置

用openpyxl的Border和Side给表格加四周边框、表头粗线、数据区细线,避免手动框选画框,附完整代码。

场景痛点

导出的表没有边框,打印出来一大片数字挤在一起,根本分不清行列。手动选中区域点框线,表多了就烦。用 openpyxl 的 Border + Side,把表头外圈画粗线、数据区画细灰线,几行代码搞定,而且每张表出来的样式一致。

用到的库

pip install openpyxl

完整代码

from openpyxl import load_workbook
from openpyxl.styles import Border, Side


def add_borders(file_path: str) -> None:
wb = load_workbook(file_path)
ws = wb.active

# 1) 定义线型:Side(style=, color=),style 用 openpyxl 内置名称
thin = Side(style="thin", color="FF999999")       # 细灰线
medium = Side(style="medium", color="FF000000")   # 粗黑线

# 2) 数据区边框:上下左右都用细线
cell_border = Border(left=thin, right=thin, top=thin, bottom=thin)

# 3) 表头下沿用粗线,和数据区拉开层次
header_bottom = Border(left=thin, right=thin, top=thin, bottom=medium)

max_col = ws.max_column
max_row = ws.max_row

# 4) 给表头每格加边框(下沿粗线)
for col in range(1, max_col + 1):
ws.cell(row=1, column=col).border = header_bottom

# 5) 给数据区每格加细线边框
for row in range(2, max_row + 1):
for col in range(1, max_col + 1):
ws.cell(row=row, column=col).border = cell_border

# 6) 整张表最外圈再套一圈粗线
outer = Border(left=medium, right=medium,
top=medium, bottom=medium)
for col in range(1, max_col + 1):
ws.cell(row=1, column=col).border = outer
ws.cell(row=max_row, column=col).border = outer
for row in range(1, max_row + 1):
ws.cell(row=row, column=1).border = outer
ws.cell(row=row, column=max_col).border = outer

wb.save(file_path)
print("边框已添加")


if __name__ == "__main__":
add_borders(r"D:\reports\销售明细.xlsx")

代码讲解

  • Side(style="thin", color="FF999999") 定义一条边的样式;常用 stylethin(细)、medium(中)、thick(粗)、dashed(虚线)、dotted(点线)。
  • Border(left=..., right=..., top=..., bottom=...) 把四条边组合成一个格子的边框,没传的边就是无线。
  • 表头那行用 header_bottom,下沿是粗黑线,视觉上把表头和数据分开。
  • 数据区循环每个格子赋 cell_border,四围都是细灰线。
  • 最后给整张表最外圈单独套粗线:顶行、底行、最左列、最右列分别赋 outer,形成外粗内细的效果。
  • 注意 border 是整体替换,后写的 outer 会覆盖前面在同一格上设的 cell_border,这正好是我们要的:外圈格子四边都粗。

运行结果

打开文件,表头下沿是粗黑线,数据区每个格子是细灰线,整张表最外圈是粗黑线,打印出来行列清晰。

注意事项

  • 线型字符串必须是 openpyxl 支持的名称,写成 "solid" 不生效,要用 "thin"/"medium"
  • 颜色同样是 8 位 ARGB,别漏了 FF 前缀。
  • 边框是按格子设的,两个相邻格子的公共边会画两次,正常看不出来但文件会稍大,数据量极大时不用纠结。
  • 合并单元格的边框要设在合并区域的外边缘,逐格设可能不显示,需要单独对合并区域的四个角处理。
  • 大表(几万格)逐格设边框会慢,但通常报表表够用。

Python Excel添加边框样式:细线粗线内外框一键设置

标签:

更新时间:2026-09-15 09:17:23

上一篇:Python openpyxl 给 Excel 单元格添加批注方法

下一篇: