MS Word Automation with docxtpl


[수정]

In case of Excel, it is used for import / export in back office or CMS. Therefore, when we implemented function, we implemented it using [XlsWriter] (https://github.com/jmcnamara/XlsxWriter). On the other hand, there was not much work to generate word documents.

This is the beginning.

I am doing monthly log analysis, making statistics, and making a report format of a Word document file. Every month, I have solved the problem by writing a script. It takes longer to write a report than that time. Of course, the time to upload to the in-house system is not easy. However, since the in-house system part is not a jurisdiction, I have been thinking about giving up and automating the report.

Since the report word document itself has a format, I thought it would be nice to be able to put only the statistics and date values in a template, and I looked up the Python library docxtpl.

docxtpl : http://docxtpl.readthedocs.io/en/latest/

    from docxtpl import DocxTemplate
    doc = DocxTemplate(template_path)
    context = render_payload
    doc.render(context)
    doc.save(output_file_path)

It is not so many star count yet, but it is concise because you are using jinja2 template and you put the template file path and the output path you want like the above code. In the middle, you can put the data in the form of context and dict in the function render. (I also like this function, it is not make, create, generate)

For example, you can use:

payload = {  
  'name' : 'ash84', 
  'date' : '2016년 5월 1일 부터  ~  2016년 5월 31일 까지', 
  'daily_avg_count' : 25000, 
  'monthly_avg_count' : 2225000
  }

doc.render(payload)  

Docxtpl seems to support the part of Hangul in the case of the body text well, in the header part of the template file, Hangul sometimes had an error in the render () process. And the part that generates the table does not seem to support well yet.

As a result, I solve a waste time of inserting data into word file. To be frank, I think the idea of doing this How much time did you develop? Or *Wasted time is greater?.