使用 python-docx 填充单词 table

Populate word table using python-docx

我有一个 table 来填充 table to populate,我对 python-docx 很陌生。我尝试使用渲染来填充它,但它只提供一台服务器作为输出:

for i in serverJson:
        doc.render(i)

其中 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)

我的问题是如何用用户输入的服务器数量填充 link 中显示的 table?

那么,您实际用这段代码做什么:

for i in serverJson:
    doc.render(i)

是多次呈现同一个文档,但只使用您提供的单个变量。相反,您需要在块本身内部提供一个 jinja for 语句,以允许它动态创建行和列。您必须对 docx 文件和 Python 代码进行操作。首先,创建一个 table 并使您的 docx 文件看起来像:

以上,我们使用了一些 jinja2 for loops 来实现以下目的:

  • 根据需要在 headers 中生成尽可能多的列
  • 生成与列表中的服务器一样多的行
  • 生成尽可能多的包含相关服务器数据的列

为了用正确的上下文填充上面的模板,请看下面的代码:

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)

以上,将产生 o.docx,看起来像: