You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python为Excel表格应用样式并设置表头为True?解决语法错误

解决Python给Excel表格应用样式及设置表头的语法错误问题

你的语法错误源于创建Table对象时,错误地将style参数嵌套在了ref的f-string内部,导致引号和参数结构混乱。下面是修正后的完整代码,同时明确设置表头为True:

import pandas
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table
from openpyxl.utils import get_column_letter

book = load_workbook('QualityReview Business-Template.xlsx')
writer = pandas.ExcelWriter('QualityReview Business-Template.xlsx', engine='openpyxl') 
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
busi_issue_date.to_excel(writer, "IssueData")

# 单独计算表格引用范围,避免f-string语法混乱
max_col = get_column_letter(busi_issue_date.shape[1])
max_row = len(busi_issue_date) + 1
table_ref = f'A1:{max_col}{max_row}'

# 正确初始化Table对象:style作为独立参数,显式设置headerRow=True
tab = Table(
    displayName="busi_issue_date",
    ref=table_ref,
    style='Table Style Medium 10',
    headerRow=True
)

worksheet = book["IssueData"]
worksheet.add_table(tab)
writer.save()

关键修改说明:

  • 将ref的计算拆分为单独变量,避免在函数参数中嵌套复杂f-string引发引号冲突
  • style是Table类的独立参数,不需要放到ref的字符串里
  • 显式设置headerRow=True(默认值就是True,显式声明让代码意图更清晰)

内容的提问来源于stack exchange,提问作者user3044949

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 04:42:53