项目中的需求是需要将前端页面展示的echarts图片生成,并将图片导出到excel中,实现图片随excel下载,在这先展示如何将echarts的图片导出到excel中,后续再补上如何导出到word模板中,使用的技术是POI
先上最终效果图
前端展示效果:

java table导出为图片 java导出图表到excel_excel


导出后到excel的效果


java table导出为图片 java导出图表到excel_java table导出为图片_02

1、前端代码:

<div class="block-title">
	<h3>标题1</h3>   
	<div>  
		<!-- 导出操作点击事件 -->
		<button type="button" onclick="doExport('census')">导出</button>   
	</div>
</div>
<!-- echarts图 -->
<div class="block-content">
	<div id="census"></div>
</div>
var census =null;
census = echarts.init(document.getElementById("census"));
	option=略
census.setOption(option);
//导出操作
function doExport(type) {
	var url_img= _ctx + "/task/oneMap/changeBase64ToImg";
	//调用echarts的getDataURL 函数将图片作为参数传到后台解析,Base64的形式转成图片
	var paramMap = {"charts":census.getDataURL({ pixelRatio: 2, backgroundColor: '#fff'})};
	var layerIndex = layer.msg('正在导出...', {icon: 16,shade: [0.5, '#f5f5f5'],scrollbar: false,offset: '0px',time: 0});
	//先将echarts的图片解析保存在项目中
	$.post(url_img,paramMap,function(msg){
		layer.closeAll();
		if(msg.state == 1){
			//图片解析后执行导出操作
			window.open(_ctx + "/task/oneMap/doExport?imgPath="+msg.imgPath1);
		}else{
			window.top.layer.mag("导出错误!请联系管理员",{icon:7});
		}
		
	});
}

2、后端代码

controller层

/**
	 * 图片base64转换
	 * 
	 * @throws Exception
	 */
	@RequestMapping("changeBase64ToImg")
	@ResponseBody
	public Map<String, Object> changeBase64ToImg(String charts) {
		Map<String, Object> map = new HashMap<String, Object>();
		// echarts获取的base64码 处理一下
		try {
			String[] arr = charts.split("base64,");
			String imgPath1 = service.changeBase64ToImg(arr[1]);
			map.put("imgPath1", imgPath1);
			map.put("state", 1);
		} catch (Exception e) {
			map.put("state", -1);
			e.printStackTrace();
		}
		return map;
	}

	//导出操作
	@RequestMapping("/doExport")
	public void export(String imgPath,HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(imgPath.indexOf("/")==0 ){
			imgPath=imgPath.substring(1);
		}
		File file = new File(imgPath);
		BufferedImage bufferedImage = ImageIO.read(file);
		ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, "png", byteArrayOut);
		byte[] data = byteArrayOut.toByteArray();//图片转字节数组

//		String rootPath=getClass().getResource("/").getFile().toString(); //获取当前项目的路径
//		String filePath=rootPath+"dot/模板.xls";//在项目resource/dot下有一个模板文件,获取路径
//		InputStream ips = new FileInputStream(filePath);
//		HSSFWorkbook workbook = new HSSFWorkbook(ips);//打开一个现有的excel文件
//		HSSFSheet sheet = workbook.getSheetAt(0);//获取第一个sheet

		HSSFWorkbook workbook = new HSSFWorkbook();//不使用打开已有的,就新建一个新的excel
		HSSFSheet sheet = workbook.createSheet();//新建sheet
		HSSFPatriarch drawingPatriarch = sheet.createDrawingPatriarch();
		/**
		 * 该构造函数有8个参数 前四个参数是控制图片在单元格的位置
		 * 分别是图片距离单元格left,top,right,bottom的像素距离
		 * 后四个参数,前2个表示图片左上角所在的cellNum和 rowNum,后2个参数对应的表示图片右下角所在的cellNum和 rowNum,
		 * excel中的cellNum和rowNum的index都是从0开始的
		 */
		HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 0, (short) 10, 13);
		try {
			drawingPatriarch.createPicture(anchor, workbook.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG));
			OutputStream output = response.getOutputStream();
			response.reset();
			//设置响应头
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String("导出到excel".getBytes("gbk"), "iso8859-1") + ".xls");
			response.setContentType("application/msexcel");
			response.setCharacterEncoding("utf-8");
			//输出workbook
			workbook.write(output);
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//下载完成后 删除临时的图片
			if(file.exists()){
				file.delete();
			}
		}
	}

service层

//Base64解析成jpg图片的形式,并保存在项目的resource/dot路径下
 public String changeBase64ToImg(String base64String){
		String rootPath=getClass().getResource("/").getFile().toString(); 
		String imgPath=rootPath+"dot/"+UUID.randomUUID().toString()+".jpg";
		boolean isok=this.Base64ToImage(base64String,imgPath);
		if(!isok){
			imgPath="";
		}
		return imgPath;
	}
	
	/**
	 * 图片base64码转换为图片并保存
	 * @param imgStr base64码
	 * @param imgFilePath 图片保存地址
	 * **/
	public  boolean Base64ToImage(String imgStr,String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
		if (StringUtil.isEmpty(imgStr)){// 图像数据为空
			return false;
		} 
		Decoder decoder = Base64.getDecoder();
		try {
			// Base64解码
			byte[] b = decoder.decode(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

至此导出操作完成,分几步操作
1、前端写好echarts图,设置点击事件
2、将echarts解析成图片保存在项目中
3、使用POI将图片导入到excel中