一、导入jar包
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
二、导出工具方法
public static void exportWordByImg(String templatePath,String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
Assert.notNull(templatePath,"模板路径不能为空");
Assert.notNull(fileName,"导出文件名不能为空");
Assert.isTrue(fileName.endsWith(".docx"),"word导出请使用docx格式");
try {
String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
}
WordImageEntity image = new WordImageEntity();
image.setHeight(50);//设置高度
image.setWidth(90);//设置宽度
image.setType(WordImageEntity.Data);//类型
image.setData(image2byte("http://localhost/upload/avatar/2019-11-12/1194160525404151808.jpg"));
params.put("imgUrl", image);
XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
String tmpPath = fileName;
FileOutputStream fos = new FileOutputStream(tmpPath);
doc.write(fos);
// 设置强制下载不打开
response.setContentType("application/force-download");
// 设置文件名
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
OutputStream out = response.getOutputStream();
doc.write(out);
out.close();
File file = new File(tmpPath);
if(file.exists()){
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// delAllFile(temDir);//这一步看具体需求,要不要删
}
}
/**
* 图片转为byte数组
*
* @param path
* @return
*/
public static byte[] image2byte(String path) throws IOException {
byte[] data = null;
URL url = null;
InputStream input = null;
try{
url = new URL(path);
HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
httpUrl.getInputStream();
input = httpUrl.getInputStream();
}catch (Exception e) {
e.printStackTrace();
return null;
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
return data;
}
解说:WordImageEntity 源码
package cn.afterturn.easypoi.word.entity;
import cn.afterturn.easypoi.entity.ImageEntity;
/** @deprecated */
@Deprecated
public class WordImageEntity extends ImageEntity {
public WordImageEntity() {
}
public WordImageEntity(byte[] data, int width, int height) {
super(data, width, height);
}
public WordImageEntity(String url, int width, int height) {
super(url, width, height);
}
}
从源码看出,该类有两个方法,可以传入URL,也可以直接利用byte[] ,博主测试后发现,利用URL 导出会有黑色背景,通过byte[] 导出一切正常。