Use Python's docxTemplate to render word files

Business background

I have been busy with development for some time. There is a business scenario that needs to dynamically fill the data obtained in the background (using Java) into the word document. At the beginning, I used Java to get the background data, use the freemarker template for data rendering, and generate word (the principle is to convert the word template into an xml file, then rename the xml file to an ftl format file, and dynamically fill the data ). Finally, python-docxTemplate is used to dynamically fill and generate word.

the difference

1. Use freemarker to render and generate word, the amount of development is large, it takes a long time, if the generated word content is too much, it is difficult to maintain (generating a leave form is still a good choice).
2. Developed with python-docxTemplate, the writing grammar is relatively clear (write the rendered grammar directly in the word document), call the render and save methods in the template to render the data into the word and save it.

Common grammar

1. 填充数据:{
    
    {
    
    var1}}
2. 判断语句:
{
    
    %p if  表达式 %} 
需显示的内容
{
    
    %p endif %}
3. 循环,一般用于表示一个整体的渲染。
{
    
    % for item  in  itemList%}
内容
{
    
    % endfor %}
4. 循环,表示在整体的部分中进行循环
{
    
    %tr for item  in  propertyDetail.projectPropertyList%}
内容
{
    
    %tr endfor %}

Document link:
https://www.it610.com/article/1279099179091640320.htm
https://docxtpl.readthedocs.io/en/latest/
http://docs.jinkan.org/docs/jinja2/templates.html

Implementation of the core code

  1. python side
安装 pip install docxtpl

from docxtpl import DocxTemplate

tpl=DoxcTemplate('模板文件路径')

// 后台请求过来的真实数据,在此使用模拟的数据
context = {
    
    
	'stuList':[{
    
    'name':'zs','age':'23','class':'二班'},	     {
    
    'name':'ww','age':'24','class':'三班班'}],
	'schoolInfo':{
    
    'address':'xxx','peoples':'125000'}
}
// 渲染 
tpl.render(context);
tpl.save('保存路径')
  1. Java side
// 从数据库中请求的数据
JSONObject param = new JSONObject();
param.put("data",gqData);

// 由于请求生成word文档时间不确定,可根据实际调节。也可使用thrift进行接口调用。
RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(-1);
factory.setConnectTimeout(-1);
restTemplate.setRequestFactory(factory);

HttpEntity<String> entity = new HttpEntity<>(param.toString() , httpHeaders);
// 执行请求-生成word
HttpEntity<String> response = restTemplate.exchange(gqPyUrl, HttpMethod.POST , entity , String.class);
// 解析返回的数据
Map remoteMap = JSONObject.parseObject(response.getBody(), Map.class);

Note: How to use thrift to call, please refer to: https://blog.csdn.net/qq_37640410/article/details/108360062
3. Template file
Insert picture description here
4. Rendering result
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_37640410/article/details/113110328