完全参考:http://t.csdnimg.cn/GwBdm
准备 新建word文档 命名model.docx
另存为.xml文件
再将文件后缀改为.ftl
再在.ftl文件中改图片的${}
搜索w:binData 修改
<w:binData w:name=“wordml://1.png”>${img}</w:binData>
依赖
<!--导出word-->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template.freemarker</artifactId>
<version>2.0.2</version>
</dependency>
controller
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/word")
public class WordController {
@GetMapping("/export1")
public void export1(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
Map<String, Object> dataMap = new HashMap<String, Object>();
//编号
dataMap.put("id", "123456");
//日期
dataMap.put("date", new SimpleDateFormat("yyyy年MM月dd日").format(new SimpleDateFormat("yyyy-MM-dd").parse("2018-09-19")));
// //附件张数
// dataMap.put("number", 1);
// //受款人
// dataMap.put("payee", "张三");
// //付款用途
// dataMap.put("use_of_payment", "test");
// //大写金额
// dataMap.put("capitalization_amount", "200.00");
// //小写金额
// dataMap.put("lowercase_amount", "100");
dataMap.put("img", getImageStr("D:\\3dmax\\yyqx\\1669536232733_2.webp"));
//Configuration 用于读取ftl文件
Configuration configuration = new Configuration(new Version("2.3.0"));
configuration.setDefaultEncoding("utf-8");
//指定路径的第二种方式,我的路径是F:/test.ftl
configuration.setDirectoryForTemplateLoading(new File("D:\\NCS\\note\\word"));//ftl文件目录
//输出文档路径及名称
File outFile = new File("D:\\note\\word\\受益人信息.doc");
//以utf-8的编码读取ftl文件
Template template = configuration.getTemplate("model.ftl", "utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
template.process(dataMap, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 本地图片地址
* @param imgFile 本地图片地址
* @return
*/
public String getImageStr(String imgFile) {
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
}
结果: