萬事第一步引包
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
第二步準備word模闆,另存為.xml的形式
word模闆圖:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2cs0TPB50dZpWT6dmeNBDOsJGcohVYsR2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLygDNyATMyQTMxEjMxAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
然後将word模闆另存為.xml
使用 NotePad++ 打開 xml 檔案
可以使用線上格式化工具進行格式化
xml内容部分截圖:
最後儲存為 FreeMarker 的模闆檔案,字尾為 ftl 格式,拷貝到項目中。不要用中文
替換資料
将要替換的資料放進map中
在模闆中找到需要替換的位置,圖檔是base64的字元串
文本以此類推
然後調用下載下傳工具類進行下載下傳即可。
涉及工具類
WordUtils
DownloadUtils
圖檔轉base64
public String getImageStr(String imgUrl) {
InputStream in = null;
byte[] data = null;
if (StringUtils.isNotEmpty(imgUrl) && !imgUrl.startsWith("http")) {
imgUrl = "http:" + imgUrl;
}
if (StringUtils.isEmpty(imgUrl)) {
//可以給預設圖
return "";
} else {
try {
in = getInputStreamByUrl(imgUrl);
} catch (Exception e) {
logger.error("加載圖檔未找到", e);
e.printStackTrace();
}
}
try {
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
logger.error("IO操作圖檔錯誤", e);
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
public InputStream getInputStreamByUrl(String strUrl) {
HttpURLConnection conn = null;
try {
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(20 * 1000);
final ByteArrayOutputStream output = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), output);
return new ByteArrayInputStream(output.toByteArray());
} catch (Exception e) {
logger.error("getInputStreamByUrl 異常,exception is {}", e);
} finally {
try {
if (conn != null) {
conn.disconnect();
}
} catch (Exception e) {
}
}
return null;
}