1.占位符创建(使用word打开)
2.话不多说上依赖
<!-- docx文档依赖 -->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document.docx</artifactId>
<version>2.0.2</version>
</dependency>
<!-- freemarker模板依赖 -->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template.freemarker</artifactId>
<version>2.0.2</version>
</dependency>
<!-- freemark依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
3.话不多说上代码
FreeMarkerController
package com.demo.freemarker;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
/**
* @author lx
* @date 2022/10/30
*/
@Slf4j
@RestController
@RequestMapping(value = "freeMarker")
public class FreeMarkerController {
@GetMapping("/download")
public void generateWord(HttpServletResponse response) throws IOException {
//获取Word模板,模板存放路径在项目的resources目录下
InputStream inputStream = new ClassPathResource("孙权劝学.docx").getInputStream();
//注册xdocreport实例并加载FreeMarker模板引擎
try {
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(inputStream, TemplateEngineKind.Freemarker);
//创建xdocreport上下文对象
IContext context = report.createContext();
//创建要替换的文本变量对象
TextParamEntity textParamEntity = new TextParamEntity();
textParamEntity.setTitle("孙权");
textParamEntity.setAuthor("司马光");
context.put("text", textParamEntity);
//设置响应内容格式(docx)application/msword(doc)
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
//设置字符集
response.setCharacterEncoding("UTF-8");
//防止中文乱码
String fileName = URLEncoder.encode("孙权劝学", "UTF-8");
//设置导出word文件格式
response.setHeader("Content-Disposition", "attachment;utf-8;filename=" + fileName + ".docx");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
ServletOutputStream out = response.getOutputStream();
report.process(context, out);
} catch (Exception e) {
log.error("export word doc error:{}", e.getMessage());
}
}
}
TextParamEntity
package com.demo.freemarker;
import lombok.Data;
@Data
public class TextParamEntity {
private String title;
private String author;
}
4.话不多说看效果
5.话不多说上模板
https://pan.baidu.com/s/1HiTIKaJStX7cVA2iSQN4oQ?pwd=0228