我正在使用 python-docx 并尝试替换表保存样式中的文本。 这就是我的桌子的样子
我已经成功地使用以下内容替换了段落:
from docx import Document
def replace_string(doc, to_replace, replacement):
for p in doc.paragraphs:
if to_replace in p.text:
inline = p.runs
for i in range(len(inline)):
if to_replace in inline[i].text:
text = inline[i].text.replace(to_replace, replacement)
inline[i].text = text
return 1
Run Code Online (Sandbox Code Playgroud)
但它不适用于表格和单元格。我也尝试过这个:
def replace_in_table(doc, to_replace, replacement):
for table in doc.tables:
for cell in table.cells:
for p in cell.paragaphs:
if to_replace in p.text:
inline = p.runs
for i in range(len(inline)):
if to_replace in inline[i].text:
text = inline[i].text.replace(to_replace, replacement)
inline[i].text = text …Run Code Online (Sandbox Code Playgroud)