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

发布时间 2023-10-20 10:38:48作者: McDelfino

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)