首页 > 技术文章 > java导出echart图到excel 多张图片导出

seeusmile-cnblog 2017-12-05 14:10 原文

分三步:

1.获取echart图的Base64码

<input type="hidden" name="img" id="img" />

$('#img').val(myChart.getDataURL("png"));

2.解码并生成图片

public void createImg(HttpServletRequest request){
String uplodapath = "D:/temp/upload";
//生成图片begin
String data = request.getParameter("img");
String imgname = "test.png";
String filedir = "D:/temp";
File file = new File(filedir);
if(!file.exists()){
file.mkdirs();
}
String[] url = data.split(",");
String u = url[1];
BASE64Decoder decoder = new BASE64Decoder();
// 生成图片
try {
// Base64解码
byte[] b = decoder.decodeBuffer(u);
OutputStream out = new FileOutputStream(new File(filedir+"\\" + imgname));
out.write(b);
out.flush();
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//图片end
}

3.读取图片到excel

try {
XSSFWorkbook wb = new XSSFWorkbook();
//下载图片到excel
//begin
BufferedImage bufferImg = null;
try {
//创建作图sheet
XSSFSheet sheet1 = null;
if(wb.getSheet("echarts")==null){
sheet1 = wb.createSheet("echarts");
}else{
sheet1 = wb.getSheet("echarts");
}
//循环读取图片插入到excel
String filedir = "D:/temp";
File file = new File(filedir);
if(file.isDirectory()){
String[] files = file.list();
//画图的顶级管理器,一个sheet只能获取一个(一定要注意这点)
XSSFDrawing patriarch = sheet1.createDrawingPatriarch();
int i = 0;
int rowbegin = 1;
int rowend = 8;
for(String _file : files){
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferImg = ImageIO.read(new File(filedir + "\\" + _file));
ImageIO.write(bufferImg, "png", byteArrayOut);
//anchor主要用于设置图片的属性
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 255, 255,(short) 1, rowbegin, (short) 5, rowend);
//插入图片
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_PNG));
i++;
rowbegin = i*8+1;
rowend = rowbegin + 8;
}
}
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("test.xls", "GBK"));
OutputStream out = response.getOutputStream();
// 写入excel文件
wb.write(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//end
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

参考来源:https://www.cnblogs.com/sun-space/p/5672373.html

http://blog.csdn.net/qq_33212500/article/details/73274799

推荐阅读