[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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2020-10-20 【493】隐马尔可夫模型