Java uses freemarker to export word documents with tables and insert pictures

Today I made a function of exporting word, including documents, tables, and inserting pictures into the tables. After several battles, I barely wrote a copy. for reference only

Because the project is built with spring boot, first we need to configure freemarker, the meaning of the configuration can be Baidu

spring:
freemarker:
cache: false
settings:
classic_compatible: true
suffix: ftl
charset: UTF-8
template-loader-path: classpath:/template

Create a new word document, write in all the content you need, and save the word document in xml format

Create a new template category as a resource storage, copy the word xml file to the template, and change the suffix to ftl

Since the list needs to be looped, we need to modify the content in the template, paramValue is the backend parameter

We still have pictures, we need to cycle through the pictures, configure them as shown in the figure below, and save them

Write another test class call test

@PostMapping("/word")
    public void word(HttpServletResponse response) throws Exception {
        List<HashMap<String,Object>> list = new ArrayList<>();
        File file = new File("C:\Users\P631694\Desktop\image\424.png");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileInputStream in = new FileInputStream(file);
        byte[] buff = new byte[1024];
        int length;
        while((length = in. read(buff)) != -1){
            out.write(buff,0,length);
        }
        in. close();
        out. close();
        for (int i=0;i<3;i + + ){
            HashMap<String,Object> valueMap = new HashMap<>();
            valueMap.put("no",i + 1);
            valueMap.put("type","occupational health");
            valueMap.put("option","Ionizing radiation studio and radioactive source? A. The system is perfect B. The system is not perfect");
            valueMap.put("result","A. Perfect system");
            valueMap.put("evaluate","management system is sound");
            valueMap.put("pict",Base64.encode(out.toByteArray()));
            list.add(valueMap);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("d1","2023");
        param.put("d2","05");
        param. put("d3","22");
        param. put("paramValue", list);
        response. reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/msword");
        response.setHeader("Content-Disposition","attachment; filename=" + "abc.doc");
        Writer writer = response. getWriter();
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("test.ftl");
        template.process(param,writer);
        writer. close();
    }

See the effect after running

Sometimes we also need to merge cells, find the place that needs to be merged and cycle, and are a pair of labels, is not merged but display value, is merged

Also build a test class to test

@PostMapping("/word")
    public void word(HttpServletResponse response) throws Exception {
        List<HashMap<String,Object>> list = new ArrayList<>();
        File file = new File("C:\Users\P631694\Desktop\image\424.png");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileInputStream in = new FileInputStream(file);
        byte[] buff = new byte[1024];
        int length;
        while((length = in. read(buff)) != -1){
            out.write(buff,0,length);
        }
        in. close();
        out. close();

        List<TestVo> testVos = new ArrayList<>();
        TestVo vo1 = new TestVo();
        vo1.setType("Occupational Health");
        vo1.setOption("Ionizing radiation studio and radioactive source? A. The system is perfect B. The system is not perfect");
        vo1.setResult("A. Perfect system");
        vo1.setEvaluate("Sound management system");
        testVos. add(vo1);
        TestVo vo2 = new TestVo();
        vo2.setType("Occupational Health");
        vo2.setOption("Ionizing radiation studio and radioactive source? A. The system is perfect B. The system is not perfect");
        vo2.setResult("A. Perfect system");
        vo2.setEvaluate("The management system is sound");
        testVos. add(vo2);
        TestVo vo3 = new TestVo();
        vo3.setType("Occupational Health 1");
        vo3.setOption("Ionizing radiation studio and radioactive source? A. The system is perfect B. The system is not perfect");
        vo3.setResult("A. Perfect system");
        vo3.setEvaluate("Sound management system");
        testVos. add(vo3);
        TestVo vo4 = new TestVo();
        vo4.setType("Occupational Health 1");
        vo4.setOption("Ionizing radiation studio and radioactive source? A. The system is perfect B. The system is not perfect");
        vo4.setResult("A. Perfect system");
        vo4.setEvaluate("The management system is sound");
        vo4.setPict(Base64.encode(out.toByteArray()));
        testVos. add(vo4);

        for (int i=0;i<testVos. size();i + + ){
            HashMap<String,Object> valueMap = new HashMap<>();
            valueMap.put("no",i + 1);
            valueMap.put("type",testVos.get(i).getType());
            valueMap.put("option",testVos.get(i).getOption());
            valueMap.put("result",testVos.get(i).getResult());
            valueMap.put("evaluate",testVos.get(i).getEvaluate());
            valueMap.put("pict", testVos.get(i).getPict());
            if(i == 0){
                valueMap. put("merge",1);
                valueMap. put("pro",0);
            }else if(testVos.get(i).getType().equals(testVos.get(i-1).getType())){
                valueMap.put("merge",1); // Merge if the strings in the same column are the same
                valueMap. put("pro",1);
            }else if(!testVos.get(i).getType().equals(testVos.get(i-1).getType())){
                valueMap. put("merge",1);
                valueMap. put("pro",0);
            }
            list.add(valueMap);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("d1","2023");
        param.put("d2","05");
        param. put("d3","22");
        param. put("paramValue", list);
        response. reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/msword");
        response.setHeader("Content-Disposition","attachment; filename=" + "abc.doc");
        Writer writer = response. getWriter();
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("abc.ftl");
        template.process(param,writer);
        writer. close();
    }

see export result

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge Java skill treeHome pageOverview 118660 people are studying systematically