请教下,关于【Python】把excel中的内容批量替换到word中 这篇文章中https://blog.csdn.net/qq_47301716/article/details/130736729,最后生成的word文件的内容格式会重新定义。
1.怎么才能实现新生成的word文件内容样式与模板同步?
2.此代码excel中如果第一列为名称那么相同名称的数据只能生成一个 word文件,怎样才能如果同名称的两行数据都生成word文档?
用了一个中午的时间, 您看下是否可以实现 , 如果没问题 创作不易 ,给个采纳哦!谢谢
具体实现方法为:
下面是代码示例:
import docx
# 读取Word模板文档
template_doc = docx.Document('template.docx')
# 创建新文档对象
new_doc = docx.Document()
# 获取模板中所有样式
for style in template_doc.styles:
# 将样式应用于新文档对象
new_doc.styles.add_style(style.name, style.type)
# 循环每个段落并将其样式应用于新文档对象
for paragraph in template_doc.paragraphs:
new_paragraph = new_doc.add_paragraph(paragraph.text)
new_paragraph.style = paragraph.style
# 循环每个表格并将其样式应用于新文档对象
for table in template_doc.tables:
new_table = new_doc.add_table(table.rows, table.columns)
for row_idx, row in enumerate(table.rows):
for col_idx, cell in enumerate(row.cells):
new_table.cell(row_idx, col_idx).text = cell.text
new_table.cell(row_idx, col_idx).style = cell.style
# 保存新文档
new_doc.save('new.docx')
下面是修改后的代码示例:
import openpyxl
import docx
# 读取Excel文件
wb = openpyxl.load_workbook('data.xlsx')
ws = wb.active
max_row = ws.max_row
# 循环每行数据并生成Word文档
count = 1
for i in range(1, max_row+1):
name = ws.cell(row=i, column=1).value
content = ws.cell(row=i, column=2).value
if name and content:
# 创建新文档对象
new_doc = docx.Document('template.docx')
# 替换文本内容
for paragraph in new_doc.paragraphs:
for run in paragraph.runs:
if "{{" in run.text:
run.text = run.text.replace("{{name}}", name)
run.text = run.text.replace("{{content}}", content)
# 保存新文档
new_doc_name = f'{name}_{count}.docx'
new_doc.save(new_doc_name)
count += 1
上述代码将每行数据中的名称和内容替换到Word模板中,并生成一个唯一的文件名。对于同样名称的数据,将会生成多个具有唯一文件名的Word文档。