添加列表循环填充

main
seele2 1 month ago
parent 35c461534a
commit 7ed5de38a2

3
.gitignore vendored

@ -1,3 +1,4 @@
/build/
/dist/
.idea
.idea
*.spec

@ -10,7 +10,7 @@
"type": "text"
},
{
"key": "{Table}",
"key": "{TableTitle}",
"value": 123,
"type": "number"
},
@ -21,23 +21,39 @@
"width": 1.25
},
{
"key": "{Table.No}",
"value": "序号测试",
"type": "text"
},
{
"key": "{Table.Name}",
"value": "名称测试",
"type": "text"
},
{
"key": "{Table.Col2}",
"value": "列2",
"type": "text"
},
{
"key": "{Table.Col3}",
"value": "列3",
"type": "text"
"key": "{Table}",
"type": "table",
"value": [
{
"No": "1",
"Name": "名称测试1",
"Col2": "列2",
"Col3": "列3"
},
{
"No": "2",
"Name": "名称测试2",
"Col2": "列2",
"Col3": "列3"
},
{
"No": "3",
"Name": "名称测试3",
"Col2": "列2",
"Col3": "列3"
},
{
"No": "4",
"Name": "名称测试4",
"Col2": "列2",
"Col3": "列3"
},
{
"No": "5",
"Name": "名称测试5",
"Col2": "列2",
"Col3": "列3"
}
]
}
]

@ -8,11 +8,11 @@ from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
def get_command_argv_by_sys():
# 默认值-用于测试
template_path = "template.docx"
template_path = "test.docx"
#template_path = "test.docx"
filename_path = "demo.docx"
datafile_path = "data.json"
datafile_path = "data_1.json"
cycle = 1
#datafile_path = "data_1.json"
cycle = 0
# 读取参数
number = len(sys.argv)
if 2 == number:
@ -61,18 +61,33 @@ def replace(template_path, filename_path, data_json):
# 表格替换
for table in document_file.tables:
for row in table.rows:
for cell in row.cells:
for datum in data_json:
if datum["key"] in cell.text:
if "text" == datum["type"]:
cell.text = cell.text.replace(datum["key"], datum["value"])
elif "picture" == datum["type"]:
paragraph = cell.paragraphs[0]
paragraph.clear()
paragraph.add_run().add_picture(datum["value"], width=Inches(datum["width"]))
elif "number" == datum["type"]:
cell.text = cell.text.replace(datum["key"], str(datum["value"]))
# 字段
row = table.rows[0]
group = None
fields = []
for cell in row.cells:
split = cell.text.replace("}","").split(".")
group = split[0] + "}"
field = split[1]
fields.append(field.strip())
# 替换
for datum in data_json:
if datum["key"] in group:
rows = len(table.rows)
values = datum["value"]
for z in range(0, len(values)):
if z < rows:
row = table.rows[z]
else:
row = table.add_row()
item = values[z]
for i in range(0, len(fields)):
field = fields[i]
if item.get(field) is not None:
row.cells[i].text = str(item.get(field))
document_file.save(filename_path)
return 0
@ -149,12 +164,6 @@ def foreach(template_path, filename_path, data_json):
return 0
def main():
params = get_command_argv_by_sys()
[template, filename, datafile, cycle] = params

Binary file not shown.
Loading…
Cancel
Save