1

How can I write multiple lines in one cell of a table with docxtpl?
I have searched some articles, but they almost doing it with coding. Can this be achieved by just fixing the docx template?

Here is my simple Python code for reading the template and JSON file, and it will convert to an output file.

import json
from docx import Document
import lxml
from docxtpl import DocxTemplate

tpl_file = ''
json_file = ''
out_file = ''

import sys, getopt


def main(argv):
   try:
      opts, args = getopt.getopt(argv,"ht:j:o:",["tfile=","jfile=","ofile="])
   except getopt.GetoptError:
      print ('gen_docx.py -t <templatefile> -j <jsonfile> -o <outputfile>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print ('gen_docx.py -t <templatefile> -j <jsonfile> -o <outputfile>')
         sys.exit()
      elif opt in ("-t", "--template"):
         tpl_file = arg
      elif opt in ("-j", "--jfile"):
         json_file = arg
      elif opt in ("-o", "--ofile"):
         out_file = arg
      
   print ('Template file is :', tpl_file)
   print ('JSON file is :', json_file)
   print ('Output file is :', out_file)
   doc = DocxTemplate(tpl_file)
   jfile = open(json_file, "r")
   context = json.load(jfile)
   doc.render(context)
   doc.save(out_file)

if __name__ == "__main__":
   main(sys.argv[1:])
{
    "history" : [
        {
            "fruit" : "apple",
            "date" : "2023/02/14",
            "summary" : [
                {"line": "test1"},
                {"line": "test2"}
            ]
        },
        {
            "fruit" : "orange",
            "date" : "2023/03/28",
            "summary" : [
                {"line" : "111"},
                {"line" : "222"},
                {"line" : "333"},
                {"line" : "444"},
                {"line" : "555"},
                {"line" : "666"},
                {"line" : "777"}
            ]
        }
    ]
}

my docx template is : docx template image

and what i got is: result image

but I want this: expected image

0 Answers0