【问题标题】:Append to text in a microsoft word table附加到 microsoft word 表中的文本
【发布时间】:2022-11-15 21:03:34
【问题描述】:

我在 MS word 中有一个表格,如下所示:

我需要修改第二个要点以将变量附加到(标题)。我可以识别单元格并返回所有文本,但我似乎无法隔离我想要更改的单行。

我到目前为止的代码是: `

import docx

# Varibles
documentname = 'yyyy-mm-dd - 0000 - Releasse Name - Instructions.docx'
title = 'Test release'

# Load document for changes
doc = docx.Document(documentname)

print(doc.tables[1].cell(2,0).text)

`

我可以根据字符串替换文本,但是我丢失了要点,这似乎不是最好的解决方案。

任何帮助都会受到极大的欢迎。

谢谢

`

import docx

# Varibles
documentname = 'yyyy-mm-dd - 0000 - Releasse Name - Instructions.docx'
title = 'Test release'

# Load document for changes
doc = docx.Document(documentname)

releasenote = doc.tables[1].cell(2,0).text

releasenotechanged = releasenote.replace("Set the value of the deployment directory package variable to","Set the value of the deployment directory package variable to " + title)
doc.tables[1].cell(2,0).text = releasenotechanged

#Save file after all updates
doc.save (documentname)

`

【问题讨论】:

    标签: python-3.x python-docx


    【解决方案1】:

    您需要访问单元格的段落才能实现类似的目的。

    一个示例 api 用例是:

    import docx
    
    doc = docx.Document()
    
    t = doc.add_table(rows=2, cols=1)
    t.style = 'Table Grid'
    
    t.cell(1, 0).add_paragraph(
        'first item in unordered list', style='List Bullet'
    )
    t.cell(1, 0).add_paragraph(
        '2nd item in unordered list', style='List Bullet'
    )
    
    t.cell(1, 0).add_paragraph(
        '3rd item in unordered list', style='List Bullet'
    )
    
    # index of para is 2, because there's always 1 empty paragraph per each cell by default
    # therefore we have 4 paras in that cell, an empty one and the three new ones
    t.cell(1, 0).paragraphs[2].text += ' ***amending 2nd item in the list***'
    
    doc.save('t1.docx')
    

    因此,在您的情况下,您可以像这样修改列表项目符号:

    doc.tables[1].cell(2,0).paragraphs[3].text += f' {title}'
    # assuming that 3rd para is `Set the value of the deployment...`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多