1.首先导入pom包
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.core</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document.docx</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template.freemarker</artifactId>
<version>2.0.2</version>
</dependency>
2.编写控制器Controller方法(附:实体类如下)
@PostMapping("/exportWord")
public void exportWord(
HttpServletResponse response, @RequestParam("orderNumber") String orderNumber)
throws IOException, XDocReportException {
// 获取Word模板,模板存放路径在项目的resources目录下
InputStream ins = this.getClass().getResourceAsStream("/template/word.docx");
// 注册xdocreport实例并加载FreeMarker模板引擎
IXDocReport report =
XDocReportRegistry.getRegistry().loadReport(ins, TemplateEngineKind.Freemarker);
// 创建xdocreport上下文对象
IContext context = report.createContext();
OrderFlowWord orderFlowWord = orderFlowService.exportWord(orderNumber);
context.put("order", orderFlowWord);
// 创建字段元数据
FieldsMetadata fm = report.createFieldsMetadata();
ServletOutputStream outputStream = response.getOutputStream();
response.setHeader(
"Content-Disposition",
"attachment;filename="
+ URLEncoder.encode(
"导出文件名称(" + orderFlowWord.getOrderNumber() + ").docx", "UTF-8"));
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/msword");
report.process(context, outputStream);
}
实体类:
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class OrderFlowWord {
private String orderNumber;
private String orderSource;
private String createDate;
private String orderType;
private String appealer;
private String phoneNumber;
private String appealDetails;
private String opinion;
private String instructions;
private String handleUnit;
private String agent;
private String agentTelPhone;
private String disposeResult;
private String signer;
private String signDate;
private Integer isAnonymity;
}