根据word模板动态导出word文档

前置条件:新建一个springboot项目

1.引jar包

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
        <groupId>com.deepoove</groupId>
         <artifactId>poi-tl</artifactId>
         <version>1.12.1</version>
 </dependency>

2.创建word模板

在resources文件夹下新建一个文件夹template(随意)新建一个test.docx内容如下:

你好:{{test1}}
我叫{{test2}}很高兴认识你
{{test3}}未来一定很好!

3.书写一个接口

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.util.PoitlIOUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


/**
 * @author wangfan
 */
@Api(tags = "测试接口")
@RestController
public class TestController {
    
    @ApiOperation("导出word")
    @GetMapping("/download")
    public void download(HttpServletResponse response){
        //为模板{{}}变量添加数据
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("test1", "java");
        dataMap.put("test2", "wangfan");
        dataMap.put("test3", "相信");
        //读取模板文件
        ClassPathResource templateFile = new ClassPathResource("/template/test.docx");
        try (OutputStream out = response.getOutputStream();
             BufferedOutputStream bos = new BufferedOutputStream(out)) {
            String fileName = "test.docx";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition","attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            String filePath = templateFile.getFile().getPath();
            //核心
            XWPFTemplate template = XWPFTemplate.compile(filePath).render(dataMap);
            template.write(bos);
            bos.flush();
            out.flush();
            PoitlIOUtils.closeQuietlyMulti(template, bos, out);
        } catch (IOException e) {
            throw new RuntimeException("文件生成失败");
        }
    }
}

完成!!!测试

更多请查看poi-tl官网:Poi-tl Documentation (deepoove.com)