Use freemarker para exportar la descarga de plantillas de Word

Tabla de contenido

1. Importar el paquete jar

2. Haz una plantilla

3. Aplicación de código

4. prueba

1. Importar el paquete jar

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>

2. Haz una plantilla

  1. Complete la plantilla con parámetros dinámicos personName, phone, address

  1. Guarde el archivo en formato xml

3. Use el bloc de notas u otras herramientas de texto para abrir el archivo de formato xml, busque los parámetros que acaba de ingresar y coloque los parámetros en ${}

4. Después de guardar, modifique el sufijo del archivo directamente a ftl

Incluso si la plantilla está hecha, simplemente escriba el código más tarde

3. Aplicación de código

capa de control

package com.xinke.sunshine_ebid.webapp;

import com.xinke.sunshine_ebid.service.TestService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@CrossOrigin
@RestController
@RequestMapping(value = "/Test")
public class TestController {
    @Resource
    private TestService testService;

    /**
     * 使用freemarker导出word模板
     * @param response
     * @throws Exception
     */
    @GetMapping("/test2")
    public void recordSheetWord2(HttpServletResponse response) throws Exception{
        testService.test2(response);
    }
}

capa de lógica de negocios

package com.xinke.sunshine_ebid.service;

import com.xinke.sunshine_ebid.common.utils.CustomXWPFDocument;
import com.xinke.sunshine_ebid.common.utils.WordUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

@Service
public class TestService {

    public void test2(HttpServletResponse response) throws Exception{
        Map<String, Object> params = new HashMap<>();

        params.put("personName","测试姓名");
        params.put("phone","18888888888");
        params.put("address","凡尔赛");

        // 需要设置的文件名
        String fileName = "文件名称";
        // 模板的文件名
        String filePath = "test2.ftl";
        response.setContentType("application/msword");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType("application/x-zip-compressed");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8") + ".docx");

        //创建配置实例
        Configuration configuration = new Configuration();
        //设置编码
        configuration.setDefaultEncoding("UTF-8");
        // 模板所在文件位置
        configuration.setDirectoryForTemplateLoading(new File("fileRecord/template/word"));
        //获取模板
        Template template = configuration.getTemplate(filePath,"UTF-8");
        // 也可以修改成生成文件存放在本地
        Writer out = response.getWriter();
        //生成文件
        template.process(params, out);
        //关闭流
        out.flush();
        out.close();

    }
}

Ejemplo de ubicación de almacenamiento de plantillas

4. prueba

Llame a la interfaz local para realizar pruebas: localhost:número de puerto/Prueba/prueba2

Exportación exitosa

Supongo que te gusta

Origin blog.csdn.net/GuaGea/article/details/131420632
Recomendado
Clasificación