1. Poi-tl官网
http://deepoove.com/poi-tl/
2.引入依赖
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.1</version>
</dependency>
3.编写Word图片模版
{{?pictures}}{{@picture}}{{/pictures}} ?和/为图片集合的开始和结束标签 @picture为每一张图片元素
4.Java代码
@RequestMapping("/test")
@RestController
public class TestController {
private static final String IMAGE_PATH = "D:\\test\\image\\";
@GetMapping("/download")
public void generateWord(HttpServletResponse response) throws IOException {
Map<String, Object> content = new HashMap<>();
List<Map<String, PictureRenderData>> pictureList = createPictureList(240, 240);
content.put("pictures", pictureList);
XWPFTemplate document = XWPFTemplate.compile(new ClassPathResource("templates/test.docx").getFile()).render(content);
setResponseHeader(response);
OutputStream os = response.getOutputStream();
document.write(os);
os.close();
}
private List<Map<String, PictureRenderData>> createPictureList(int width, int height) {
List<Map<String, PictureRenderData>> list = new ArrayList<>();
list.add(createPictureMap("微信图片_20231217213601.jpg", width, height));
list.add(createPictureMap("190623-1701774383944b.jpg", width, height));
list.add(createPictureMap("202054-1695298854fd7d.jpg", width, height));
return list;
}
private Map<String, PictureRenderData> createPictureMap(String imageName, int width, int height) {
Map<String, PictureRenderData> map = new HashMap<>();
map.put("picture", Pictures.ofLocal(IMAGE_PATH + imageName).size(width, height).create());
return map;
}
private void setResponseHeader(HttpServletResponse response) {
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition",
"attachment;filename=user_word_" + System.currentTimeMillis() + ".docx");
}
}