https://www.pythonf.cn/read/149081 Python自动将Excel数据填充到word的指定位置,Word,中
具体代码如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from docxtpl import DocxTemplate
from openpyxl import load_workbook
import os
def replace(obj):
if obj is None:
obj = ''
return obj
# 加载要填入的数据
wb = load_workbook(r"./detailContent.xlsx")
ws = wb['sheet1']
contexts = []
for row in range(2, ws.max_row + 1):
name = ws["A" + str(row)].value
#c_name = ws["B" + str(row)].value
ziduanName = ws["C" + str(row)].value
# num = ws["D" + str(row)].value
# time = ws["E" + str(row)].value
# time = str(time)[:-9]
# money = ws["F" + str(row)].value
# address = ws["G" + str(row)].value
# replace_peo = ws["H" + str(row)].value
# context = {"name": name, "c_name": c_name, "code": code, "num": num, "time": time,
# "money": money, "address": address, "replace_peo": replace_peo}
context = {"name":name,"ziduanName":ziduanName}
contexts.append(context)
#contexts
print(contexts)
print(len(contexts))
# 创建要保存的文件夹
os.mkdir("./word1")
for context in contexts:
print(context)
tpl = DocxTemplate(r"./model.docx")
tpl.render(context)
tpl.save("./word1/数据表-{}.docx".format(context["name"]))