easypoi导出图片问题源码修改(版本3.2.0)

既然要修改源码部分bug问题,那么就把使用一并讲了吧:
补充依赖文件:

<!-- Excel easypoi -->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>3.2.0</version>
    <exclusions>
        <exclusion>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </exclusion>
    </exclusions>
</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>
<!-- Excel easypoi -->

1.首先,导出图片对象参数设置如下:

/**
 * 证件URL
 */
@Excel(name = "证件",orderNum = "3",type = 2,width = 100D,height = 100D)
private String imgPath;

设置type = 2表示导出图片

2.修改源码部分:

package com.lbd99.scm.credit.service;

import cn.afterturn.easypoi.cache.manager.FileLoaderImpl;
import cn.afterturn.easypoi.cache.manager.IFileLoader;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * easyPoi源码方法重写,源码出现bug,此处重写方法修复bug,使用时重新引入
 *
 * 针对图片导出功能
 *
 * @author Tom
 * @date 2020-01-08
 */
public class FileLoaderImplOnce implements IFileLoader {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileLoaderImpl.class);

    @Override
    public byte[] getFile(String url) {
        InputStream fileis = null;
        ByteArrayOutputStream baos = null;
        try {

            //判断是否是网络地址
            if (url.startsWith("http")) {
                URL urlObj = new URL(url);
                URLConnection urlConnection = urlObj.openConnection();
                urlConnection.setConnectTimeout(3 * 1000);
                urlConnection.setReadTimeout(60 * 1000);
                urlConnection.setDoInput(true);
                urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
                fileis = urlConnection.getInputStream();

            } else {
                //先用绝对路径查询,再查询相对路径
                try {
                    fileis = new FileInputStream(url);
                } catch (FileNotFoundException e) {
                    //获取项目文件
                    fileis = FileLoaderImpl.class.getClassLoader().getResourceAsStream(url);
                    if (fileis == null) {
                        //最后再拿相对文件路径
                        String path = PoiPublicUtil.getWebRootPath(url);
                        fileis = new FileInputStream(path);
                    }
                }
            }

            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fileis.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos.toByteArray();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(fileis);
            IOUtils.closeQuietly(baos);
        }
        LOGGER.error(fileis + "这个路径文件没有找到,请查询");
        return null;
    }
}

此处源码主要修改http方式的链接时间,项目实测,60毫秒对于大文件无法获取。

源码LoadingCache方法重写:

package com.lbd99.scm.credit.service;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.poi.util.IOUtils;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import cn.afterturn.easypoi.cache.manager.POICacheManager;

/**
 * easyPoi方法重写,源码有bug,此方法重写后进行调用
 *
 * 针对图片导出功能
 *
 * @author Tom
 * @date 2020-01-08
 */
public class ImageLoadCache {

    public static LoadingCache<String, byte[]> loadingCache;

    static {
        loadingCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.DAYS)
                .maximumSize(2000).build(new CacheLoader<String, byte[]>() {
                    @Override
                    public byte[] load(String imagePath) throws Exception {
                        InputStream is = POICacheManager.getFile(imagePath);
                        BufferedImage bufferImg = ImageIO.read(is);
                        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                        try {
                            ImageIO.write(bufferImg,
                                    imagePath.substring(imagePath.lastIndexOf(".") + 1, imagePath.length()),
                                    byteArrayOut);
                            return byteArrayOut.toByteArray();
                        } finally {
                            IOUtils.closeQuietly(is);
                            IOUtils.closeQuietly(byteArrayOut);
                        }
                    }
                });
    }
}

此处主要解决,图片地址中存在".“的情况,所以从后开始取”."的部分

3.在设置导出参数之前,添加如下方法:

POICacheManager.setFileLoderOnce(new FileLoaderImplOnce());
ImageCache.setLoadingCache(ImageLoadCache.loadingCache);

目的:覆盖之前源码。

4.项目实列代码如下:

List<ExportView> paramsList = new ArrayList<>();
Map<String,Object> map1 = new HashMap<>();
map1.put("fileName","授信证件资料明细表");
map1.put("title","授信证件资料明细");
map1.put("sheetName","授信证件资料明细表");
map1.put("tClass",new CreditTciItem());
POICacheManager.setFileLoderOnce(new FileLoaderImplOnce());
ImageCache.setLoadingCache(ImageLoadCache.loadingCache);

String path = "http://*******.com/scmplus";
for(CreditTciItem i : list3){
	if(StringUtils.isNotBlank(i.getImgPath())){
		i.setImgPath(path + i.getImgPath());
	}
}
map1.put("datas",list3);
paramsList.add(getExportDate(map1));
/**
	 * 封装导出Excel参数
	 * @param map
	 * @return
	 */
	public ExportView getExportDate(Map<String,Object> map) throws Exception {
		HashMap<Map<String,Boolean>, List<ExcelExportEntity>> addMap = new HashMap<>();
		HashMap<String, Boolean> map1 = new HashMap<>();
		map1.put(map.get("fileName").toString(),true);
		List<ExcelExportEntity> excelExportEntities = new ArrayList<>();
		ExcelExportEntity excelExportEntity = new ExcelExportEntity();
		excelExportEntities.add(excelExportEntity);
		addMap.put(map1,excelExportEntities);
		String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		ExportView exportView = new ExportView(map.get("fileName").toString() + time,map.get("title").toString(),map.get("sheetName").toString());
		exportView.setExportMode(ExportModeEnum.SINGLE);
		exportView.setEntityCls(map.get("tClass").getClass());
		exportView.setAddMap(addMap);
		ExportParams exportParams = exportView.getExportParams();
		exportParams.setType(ExcelType.HSSF);
		exportParams.setTitleHeight((short) 15);
		exportParams.setStyle(ExcelExportStylerImpl.class);
		exportView.setDataList((List<Object>)map.get("datas"));
		return exportView;
	}

你可能感兴趣的:(JAVA)