使用EasyExcel导出图片及异常处理

1、使用String类型导出   定义自己的Converter,不使用默认的StringImageConverter

如果图片路径为空或者图片路径是错误的,返回相应的内容

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IoUtils;
import com.njyjz.common.util.Validater;

public class MyStringImageConverter implements Converter<String>
{
    @Override
    public Class supportJavaTypeKey()
    {
        return String.class;
    }
    
    @Override
    public CellDataTypeEnum supportExcelTypeKey()
    {
        return CellDataTypeEnum.IMAGE;
    }
    
    @Override
    public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration)
    {
        throw new UnsupportedOperationException("Cannot convert images to string");
    }
    
    // 图片失效处理
    @Override
    public CellData convertToExcelData(String value, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration)
        throws IOException
    {
        InputStream inputStream = null;
        try
        {
            if(Validater.isEmptyString(value))
            {
                return new CellData("图片路径为空");
            }
            URL urlValue = new URL(value);
            // 开启连接
            URLConnection uc = urlValue.openConnection();
            // 获取响应状态
            int statusCode = ((HttpURLConnection)uc).getResponseCode();
            switch (statusCode)
            {
                case 200:
                    inputStream = urlValue.openStream();
                    break;
                default:
                    return new CellData("无法加载图片");
            }
            byte[] bytes = IoUtils.toByteArray(inputStream);
            return new CellData(bytes);
        }
        catch (ConnectException exception)
        {
            return new CellData("无法加载图片");
        }
        catch (FileNotFoundException fileNotFoundException)
        {
            return new CellData("无法加载图片");
        }
        finally
        {
            if (inputStream != null)
            {
                inputStream.close();
            }
        }
    }
    
}

2、更改图片字段注解

@ExcelProperty(value = "扫描图像", index = 0, converter = MyStringImageConverter.class)
private String fileUrl;

3、导出样例

 

 

 

posted @ 2021-09-15 17:08  云村的王子  阅读(3667)  评论(0编辑  收藏  举报