用python替换和循环插入excel的内容
目的:
1.有一个word模板和一个有数据的excel表格
2.需要将excel中的数据经过更改成需要的字符串插入word段落中
3.更改word中的字符串
4.写一个现阶段可以用的程序,并用作以后更新迭代复用。
过程:
1.原word内容

2.excel数据

3.代码
import pandas as pd
import docxdf_1 = pd.read_excel('./test.xlsx', dtype = str, sheet_name = 0)
doc = docx.Document('./test.docx')
insert_marker = '{{INSERT_DATA_HERE}}'
replace_dict = {'天': '地'}
for paragraph in doc.paragraphs:if insert_marker in paragraph.text:for index, row in df_1.iterrows():sentence = f"我叫{row['姓名']},现在{row['年龄']}岁,住在{row['地址']},联系方式是{row['电话']}。"paragraph.insert_paragraph_before(sentence)paragraph.text = paragraph.text.replace(insert_marker, "")else:for old_text, new_text in replace_dict.items():if old_text in paragraph.text:paragraph.text = paragraph.text.replace(old_text, new_text)doc.save('./output.docx')
4.生成word内容
