【问题标题】:Bold part of string in table python docx表python docx中字符串的粗体部分
【发布时间】:2022-10-24 00:15:55
【问题描述】:

我正在遍历两列,并想将一个列表的文本添加到一个表格单元格中,然后是另一个,我想加粗另一个列表的内容。到目前为止,这是我想出的:

document = Document()
table = document.add_table(rows=int(np.ceil(len(line_items_sample)/3)), cols=3)
index = 0
for item,quantity in zip(line_items_sample['title'].tolist(), line_items_sample['quantity']):
    print(item)
    if index % 3 == 0:
        row = table.add_row().cells
        row[0].text = item.upper() + ' ' + quantity
    if index % 3 == 1:
        row[1].text = item.upper() + ' ' + quantity
        
    else:
        row[2].text = item.upper() + ' ' + quantity
    index = index + 1

为了清楚起见,我希望项目保持大写和粗体。我认为我遇到的问题是了解如何在表格的一个单元格中拥有两种不同的样式。

【问题讨论】:

    标签: python-3.x python-docx


    【解决方案1】:

    在我提出第一个答案后,我不得不重新阅读您的要求,这没有考虑到两个列表。

    这是完成用例的一种方法。

    from docx import Document
    
    document = Document()
    records_one = ['Dogs', 'Cats', 'Birds']
    records_two = ['Bark', 'Meow', 'Chirp']
    
    table = document.add_table(rows=1, cols=1)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'combined'
    
    for item_one, item_two in zip(records_one, records_two):
        row_cells = table.add_row().cells
        part_one_cell = row_cells[0]
        part_one_cell.paragraphs[0].add_run(item_one)
        part_one_cell.paragraphs[0].add_run(f' {item_two.upper()}').bold = True
    document.save('demo.docx')
    
    

    输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-27
      • 2015-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多