maven 所需依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.3.1</version>
</dependency>
读取服务器(网路)的word模板文件并替换自定义的数据(图片),输出到本地文件夹
public static void main(String[] args) throws Exception {
ConfigureBuilder builder = Configure.builder();
Map map = Maps.newHashMap();
map.put("id", "123");
map.put("img", Pictures.ofUrl("http://192.168.1.16:9000/common/isite90-form-server/20220311/1646965853625/202203111030536250000002-bea34e6e-0c71-4eb5-8f47-6247ac140398.png", PictureType.JPEG).size(60, 60).create());
String paht = "http://192.168.1.16:9000/common/isite90-form-server/20220321/1647826081579/202203210928015790000002-41db51fd-ec98-4c1e-b08e-1e7a815604c5.docx";
URL url = new URL(paht);
HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
//设置请求方式为"GET"
httpUrl.setRequestMethod("GET");
//超时响应时间为5秒
httpUrl.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
InputStream inStream = httpUrl.getInputStream();
XWPFTemplate template = XWPFTemplate.compile(inStream, builder.build()).render(map);
template.writeAndClose(new FileOutputStream("D:\\test\\output.docx"));
}
读取服务器(网路)的word模板文件并替换自定义的数据(图片),返回输出到浏览器
// 替换word文档数据(包括图片)并导出
public static ResultBody replaceWord(HttpServletResponse response, Map<String, Object> map, String templateFilePath, String outFileName) throws Exception {
ConfigureBuilder builder = Configure.builder();
map.put("id", "123");
map.put("img", Pictures.ofUrl("http://192.168.1.16:9000/common/isite90-form-server/20220311/1646965853625/202203111030536250000002-bea34e6e-0c71-4eb5-8f47-6247ac140398.png", PictureType.JPEG).size(60, 60).create());
// 读取远程服务器的文件
URL url = new URL(templateFilePath);
HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
//设置请求方式为"GET"
httpUrl.setRequestMethod("GET");
//超时响应时间为5秒
httpUrl.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
InputStream inStream = httpUrl.getInputStream();
// 读入 输入文件流
XWPFTemplate template = XWPFTemplate.compile(inStream, builder.build()).render(map);
// XWPFTemplate template1 = XWPFTemplate.compile(new File("D:\\test\\td.docx"), builder.build()).render(map);
// template.writeAndClose(new FileOutputStream("D:\\test\\output.docx"));
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode( outFileName+".docx", "UTF-8"));
OutputStream out = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(bos);
bos.flush();
out.flush();
PoitlIOUtils.closeQuietlyMulti(template, bos, out);
return null;
}