注意:导入的图片需为浮动图片
官方API:http://easypoi.mydoc.io
1.依赖
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
2.代码
ImportExcel.java:
public static List<GoodsHasImgModel> analysisExcelFileEasyPoi(MultipartFile file) throws Exception {
ImportParams params = new ImportParams();
params.setNeedSave(false);
//解析后的图片字段存放的是图片的地址,需要在GoodsModel中配置图片存放路径
List<GoodsModel> result = ExcelImportUtil.importExcel(file.getInputStream(), GoodsModel.class, params);
for (GoodsModel goodsModel : result) {
if (StringUtils.isNotEmpty(goodsModel.getGoodsPic())) {
//将图片文件转为base64图片
File file1 = new File(goodsModel.getGoodsPic());
FileInputStream inputStream = new FileInputStream(file1);
byte[] buffer = new byte[inputStream.available()];
if (inputStream.read(buffer) == -1) {
inputStream.close();
}
StringBuilder imageBase64 = new StringBuilder(Base64.getEncoder().encodeToString(buffer));
goodsHasImgModel.setGoodsPic(new String(imageBase64));
}
}
return result;
}
@ExcelTarget("goodsEntity")
@Data
@Component
public class GoodsHasImgModel {
@Excel(name = "商品名称")
private String goodsName;
//savePath配置的是解析excel后存放图片的路径
@Excel(name = "商品照片", type = 2, width = 20, height = 10, imageType = 1, savePath = "/home/file/img")
private String goodsPic;
...
}
删除临时图片
String[] fileList = new File(savePath).list();
for (String str : fileList) {
File file1 = new File(savePath + "/" + str);
if (file1.isFile()) {
logger.info("清理图片缓存:" + str + (file1.delete() ? "成功" : "失败"));
}
}