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

Python docx表格单元格内部分文本加粗实现问题

在python-docx表格单元格内实现混合文本样式

你的需求是将大写后的item和加粗的quantity放在同一表格单元格,但直接通过cell.text赋值只能设置纯文本,无法实现混合样式。解决思路是利用python-docx的段落run对象,每个run可以单独设置样式。

修正后的完整代码

from docx import Document
import numpy as np

document = Document()
# 初始化表格时设rows=0,后续通过add_row添加行避免空行
table = document.add_table(rows=0, cols=3)
index = 0
row = None

for item, quantity in zip(line_items_sample['title'].tolist(), line_items_sample['quantity']):
    if index % 3 == 0:
        # 每3个条目新增一行
        row = table.add_row().cells
        # 处理第一个单元格
        cell = row[0]
        p = cell.paragraphs[0]
        p.add_run(item.upper())  # 添加大写的item
        p.add_run(' ')  # 添加空格分隔
        p.add_run(str(quantity)).bold = True  # 添加加粗的quantity
    elif index % 3 == 1:
        # 处理第二个单元格
        cell = row[1]
        p = cell.paragraphs[0]
        p.add_run(item.upper())
        p.add_run(' ')
        p.add_run(str(quantity)).bold = True
    else:
        # 处理第三个单元格
        cell = row[2]
        p = cell.paragraphs[0]
        p.add_run(item.upper())
        p.add_run(' ')
        p.add_run(str(quantity)).bold = True
    index += 1

# 保存文档
document.save('output.docx')

关键说明

  1. 避免空行问题:原代码初始化表格时设置了rows=int(np.ceil(len(line_items_sample)/3)),后续又调用add_row(),会导致表格开头出现空行,因此改为rows=0。
  2. 混合样式实现:每个表格单元格默认包含一个段落,通过cell.paragraphs[0]获取该段落,然后依次添加三个run:
    • 第一个run写入大写后的item
    • 第二个run写入空格用于分隔
    • 第三个run写入quantity并设置bold=True实现加粗
  3. 循环逻辑修正:原代码的if-else结构存在逻辑错误(index%3==0时会同时执行else分支),改为if-elif-else确保每个index只对应一个单元格的赋值操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:20:30