CellDataTypeEnum.IMAGE ----> CellDataTypeEnum.RICH_TEXT_STRING
导出图片,导出二维码等工具类:
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IoUtils;
import com.alibaba.excel.util.StringUtils;
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;
public class MyStringImageConverter implements Converter<String>
{
@Override
public Class supportJavaTypeKey()
{
return String.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey()
{
return CellDataTypeEnum.RICH_TEXT_STRING;
}
@Override
public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration)
{
throw new UnsupportedOperationException("Cannot convert images to string");
}
// 图片失效处理
@Override
public WriteCellData<Object> convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration)
throws IOException
{
InputStream inputStream = null;
try
{
if(StringUtils.isEmpty(value))
{
return new WriteCellData<>("图片路径为空");
}
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 WriteCellData<>("无法加载图片");
}
byte[] bytes = IoUtils.toByteArray(inputStream);
WriteCellData<Object> cellData = new WriteCellData<>(bytes);
cellData.setType(CellDataTypeEnum.NUMBER);
return cellData;
}
catch (ConnectException exception)
{
return new WriteCellData<>("无法加载图片");
}
catch (FileNotFoundException fileNotFoundException)
{
return new WriteCellData<>("无法加载图片");
}
finally
{
if (inputStream != null)
{
inputStream.close();
}
}
}
}