Python办公自动化教程(008):设置excel单元格边框和背景颜色

3.2 添加边框

示例代码

python 复制代码
import openpyxl
from openpyxl.styles import Border, Side

# 1️⃣ 创建 Excel 工作簿
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = "球员信息"

# 2️⃣ 定义边框样式(细线边框)
thin_border = Border(
    left=Side(style="thin"),
    right=Side(style="thin"),
    top=Side(style="thin"),
    bottom=Side(style="thin"),
)

# 3️⃣ 写入数据
data = [
    ["球员", "球队"],
    ["凯文·杜兰特", "太阳"],
    ["德文·布克", "太阳"],
    ["布拉德利·比尔", "太阳"],
    ["克里斯·保罗", "勇士"],
    ["斯蒂芬·库里", "勇士"]
]

for row_idx, row in enumerate(data, start=1):  # 从 Excel 第 1 行开始
    for col_idx, value in enumerate(row, start=1):  # 从 Excel 第 1 列开始
        cell = sheet.cell(row=row_idx, column=col_idx, value=value)
        cell.border = thin_border  # 应用边框

# 4️⃣ 保存文件
wb.save("suns.xlsx")
wb.close()

实现效果

你可以更改 Side(style="thin") 来调整边框:

  • 细线Side(style="thin")
  • 粗线Side(style="thick")
  • 虚线Side(style="dashed")
  • 点线Side(style="dotted")
  • 双线Side(style="double")

3.3 设置背景颜色

示例代码

python 复制代码
import openpyxl
from openpyxl.styles import PatternFill, Border, Side, Font

# 1️⃣ 创建 Excel 工作簿
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = "球员信息"

# 2️⃣ 定义边框样式(细线边框)
thin_border = Border(
    left=Side(style="thin"),
    right=Side(style="thin"),
    top=Side(style="thin"),
    bottom=Side(style="thin"),
)

# 3️⃣ 定义填充颜色 & 字体样式
header_fill = PatternFill(fill_type="solid", fgColor="ffffff")  # 浅灰色(表头)
suns_fill = PatternFill(fill_type="solid", fgColor="FF8C00")  # 深橙色(太阳队)
warriors_fill = PatternFill(fill_type="solid", fgColor="00008B")  # 深蓝色(勇士队)
default_fill = PatternFill(fill_type="solid", fgColor="333333")  # 深灰色(其他球队)

# **字体样式**
header_font = Font(color="000000", bold=True)  # **表头字体:黑色 + 加粗**
white_font = Font(color="FFFFFF", bold=True)  # **数据字体:白色 + 加粗**

# 4️⃣ 写入数据
data = [
    ["球员", "球队"],  # 表头
    ["凯文·杜兰特", "太阳"],
    ["德文·布克", "太阳"],
    ["布拉德利·比尔", "太阳"],
    ["克里斯·保罗", "马刺"],
    ["斯蒂芬·库里", "勇士"],
    ["扬尼斯·阿德托昆博", "雄鹿"]
]

for row_idx, row in enumerate(data, start=1):  # 从 Excel 第 1 行开始
    # 5️⃣ 确定整行颜色
    if row_idx == 1:
        row_fill = header_fill  # **表头 浅灰色**
        row_font = header_font  # **表头字体 黑色**
    elif row[1] == "太阳":
        row_fill = suns_fill  # **太阳队 深橙色**
        row_font = white_font  # **白色字体**
    elif row[1] == "勇士":
        row_fill = warriors_fill  # **勇士队 深蓝色**
        row_font = white_font  # **白色字体**
    else:
        row_fill = default_fill  # **其他队伍 深灰色**
        row_font = white_font  # **白色字体**

    for col_idx, value in enumerate(row, start=1):  # 从 Excel 第 1 列开始
        cell = sheet.cell(row=row_idx, column=col_idx, value=value)
        cell.border = thin_border  # 应用边框
        cell.fill = row_fill  # 应用整行背景色
        cell.font = row_font  # 应用字体颜色

# 6️⃣ 保存文件
wb.save("nba_teams_header_black.xlsx")
wb.close()

实现效果

颜色自定义

  • 表头背景色 可调整 header_fill = PatternFill(fill_type="solid", fgColor="XXXXXX")
  • 表头字体颜色 header_font = Font(color="000000", bold=True)000000 为黑色)
  • 数据字体颜色 white_font = Font(color="FFFFFF", bold=True)FFFFFF 为白色)
相关推荐
花酒锄作田7 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪11 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽11 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战12 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋17 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama