Tar*_*wak 3 python ms-word jinja2 python-docx
我有一个表来填充要填充的表,我对 python-docx 很陌生。我尝试使用渲染来填充它,但它只作为输出提供给一台服务器:
for i in serverJson:
doc.render(i)
Run Code Online (Sandbox Code Playgroud)
其中 serverJson 是用户输入的服务器列表。例如:
for i in appserver:
server_1={"component":"Tomcat","comp_version":"7","server":i,
"app_port":"5000","db_sid":" ","db_port":"200"}
server_2={"component":"Apache","comp_version": "2.4","server":i,
"app_port":" ","db_sid":" ","db_port":"200"}
serverJson.append(server_1)
serverJson.append(server_2)
Run Code Online (Sandbox Code Playgroud)
我的问题是如何用用户输入的服务器数量填充链接中显示的表格?
那么,您实际上正在使用这段代码做什么:
for i in serverJson:
doc.render(i)
Run Code Online (Sandbox Code Playgroud)
是多次渲染同一个文档,但仅使用您提供的单个变量。for相反,您需要在块本身内提供 jinja语句,以允许它动态创建行和列。您必须对docx文件和 Python 代码进行操作。首先,创建一个表并使您的docx文件如下所示:
上面,我们使用一些 jinja2for loops来实现以下目的:
为了使用正确的上下文填充上述模板,请查看以下代码:
from docxtpl import DocxTemplate
import os,sys
#Just change these according to your needs
inputFileName = "i.docx"
outputFileName = "o.docx"
#This is done to obtain the absolute paths to the input and output documents,
#because it is more reliable than using the relative path
basedir = os.path.dirname(sys.argv[0])
path = os.path.join(basedir, "", inputFileName)
outpath = os.path.join(basedir, "", outputFileName)
template = DocxTemplate(path)
#Specify all your headers in the headers column
context = {
'headers' : ['Component', 'Component Version', 'Server FQDN', 'Application port', 'DB SID', 'DB Port', 'Infos'],
'servers': []
}
#Fictious appserver list
appserver = ['a','b']
#Add data to servers 1 and 2 using a list and not a dict, remember to add
#an empty string for the Infos, as well, otherwise the border won't be drawn
for i in appserver:
server_1= ["Tomcat",7,i,5000," ",200,""]
server_2= ["Apache",2.4,i," "," ",200,""]
context['servers'].append(server_1)
context['servers'].append(server_2)
template.render(context)
template.save(outpath)
Run Code Online (Sandbox Code Playgroud)
以上,将产生o.docx如下所示:
| 归档时间: |
|
| 查看次数: |
4574 次 |
| 最近记录: |