alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[921] Replace texts, copy formats, align paragraphs in a Word document by Python

The whole steps of this function are as follows:

  • Open the Word document.
  • Replace the text with the new text.
  • Copy the format from the source cell to the target cell.
  • Set the horizontal alignment of a cell in the table.
  • Save the Word document.

def change_cell_formatting(docx_file_path):
"""
It is used to change the cell formatting of the table. This method is only used in Map5_3.
Args:
docx_file_path (string): The file path of the Word document.
"""
# Open the Word document
doc = Document(docx_file_path)
# Define the text you want to find and replace
old_text = "Landslip Erosion Risk"
new_text = "Not identified"
# Check if the table contains the old text and replace it with the new text
for cell in doc.tables[51].rows[1].cells:
if old_text in cell.text:
cell.text = cell.text.replace(old_text, new_text)
# Get the source and target cells
source_cell = doc.tables[51].cell(1, 1)
target_cell = doc.tables[51].cell(1, 0)
# Copy formatting from the source cell to the target cell
for source_paragraph, target_paragraph in zip(source_cell.paragraphs, target_cell.paragraphs):
for source_run, target_run in zip(source_paragraph.runs, target_paragraph.runs):
target_run.font.size = Pt(source_run.font.size.pt)
target_run.font.name = source_run.font.name
# set the horizontal alignment of a cell in a table
for paragraph in target_cell.paragraphs:
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
# Save the modified document
doc.save(docx_file_path)

 

posted on   McDelfino  阅读(6)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-10-20 【493】隐马尔可夫模型
点击右上角即可分享
微信分享提示