`

echarts 生成统计图时,自动保存图片到服务器,并使用freemarker生成word

阅读更多

echarts 生成统计图时,自动保存图片到服务器,并使用freemarker生成word。

 

1.项目工程截图如下:

需要echarts包和生成word的freemarker-2.3.8.jar包

2.index.jsp页面中的代码:

[html] view plaincopy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>ECharts 生成报表 并保存图片</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.   </head>  
  22.     
  23.   <body>  
  24.     <!-- 为ECharts准备一个具备大小(宽高)的Dom -->  
  25.     <div id="main" style="height:400px"></div>  
  26.     <!-- ECharts单文件引入 -->  
  27.     <script src="<%=basePath %>js/echarts/build/dist/echarts.js"></script>  
  28.     <script type="text/javascript">  
  29.         // 路径配置  
  30.         require.config({  
  31.             paths: {  
  32.                 echarts: '<%=basePath %>js/echarts/build/dist'  
  33.             }  
  34.         });  
  35.           
  36.         // 使用  
  37.         require(  
  38.             [  
  39.                 'echarts',  
  40.                 'echarts/chart/bar' // 使用柱状图就加载bar模块,按需加载  
  41.             ],  
  42.             function (ec) {  
  43.                 // 基于准备好的dom,初始化echarts图表  
  44.                 var myChart = ec.init(document.getElementById('main'));   
  45.                   
  46.                 var option = {  
  47.                     tooltip: {  
  48.                         show: true  
  49.                     },  
  50.                     legend: {  
  51.                         data:['销量']  
  52.                     },  
  53.                     xAxis : [  
  54.                         {  
  55.                             type : 'category',  
  56.                             data : ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]  
  57.                         }  
  58.                     ],  
  59.                     yAxis : [  
  60.                         {  
  61.                             type : 'value'  
  62.                         }  
  63.                     ],  
  64.                     series : [  
  65.                         {  
  66.                             "name":"销量",  
  67.                             "type":"bar",  
  68.                             "data":[5, 20, 40, 10, 10, 20]  
  69.                         }  
  70.                     ]  
  71.                 };  
  72.           
  73.                 // 为echarts对象加载数据   
  74.                 myChart.setOption(option);   
  75.                 setTimeout(exportImage, 2000);  
  76.                 function exportImage(){  
  77.                     var data = "a="+encodeURIComponent(myChart.getDataURL("png"));  
  78.                     var xmlhttp;  
  79.                     if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari  
  80.                         xmlhttp = new XMLHttpRequest();  
  81.                     } else { // code for IE6, IE5  
  82.                         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  
  83.                     }  
  84.                     xmlhttp.open("POST","<%=path%>/servlet/saveImage",true);  
  85.                     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");  
  86.                     xmlhttp.onreadystatechange = function() {  
  87.                         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {  
  88.                             alert("保存成功");  
  89.                         }  
  90.                     }  
  91.                     xmlhttp.send(data);  
  92.                 }  
  93.                   
  94.             }  
  95.         );  
  96.     </script>  
  97. </body>  
  98. </html>  

3.web.xml

[html] view plaincopy
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <display-name></display-name>   
  8.   <welcome-file-list>  
  9.     <welcome-file>index.jsp</welcome-file>  
  10.   </welcome-file-list>  
  11.     
  12.   <servlet>  
  13.     <servlet-name>saveImage</servlet-name>  
  14.     <servlet-class>com.servlet.SaveImage</servlet-class>  
  15.   </servlet>  
  16.   
  17.   <servlet-mapping>  
  18.     <servlet-name>saveImage</servlet-name>  
  19.     <url-pattern>/servlet/saveImage</url-pattern>  
  20.   </servlet-mapping>  
  21. </web-app>  

4.SaveImage.java

[html] view plaincopy
 
  1. package com.servlet;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import java.util.ArrayList;  
  10. import java.util.HashMap;  
  11. import java.util.List;  
  12. import java.util.Map;  
  13.   
  14. import javax.servlet.ServletException;  
  15. import javax.servlet.http.HttpServlet;  
  16. import javax.servlet.http.HttpServletRequest;  
  17. import javax.servlet.http.HttpServletResponse;  
  18.   
  19. import com.word.WordUtil;  
  20.   
  21. import sun.misc.BASE64Decoder;  
  22. import sun.misc.BASE64Encoder;  
  23.   
  24. public class SaveImage extends HttpServlet {  
  25.     private static final long serialVersionUID = -1915463532411657451L;  
  26.        
  27.     public void init() throws ServletException {    
  28.          
  29.     }   
  30.     protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {  
  31.           
  32.     }  
  33.    
  34.     protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {  
  35.         String a = request.getParameter("a");  
  36.         try {  
  37.             String[] url = a.split(",");  
  38.             String u = url[1];  
  39.             // Base64解码  
  40.             byte[] b = new BASE64Decoder().decodeBuffer(u);  
  41.             WordUtil wordUtil = new WordUtil();  
  42.             String fileStr = wordUtil.saveFile();   
  43.             // 生成图片  
  44.             OutputStream out = new FileOutputStream(new File(fileStr+"\\test.png"));  
  45.             out.write(b);  
  46.             out.flush();  
  47.             out.close();  
  48.               
  49.             //数据模拟,如果是真实编写,可以建service层,dao层进行数据的获取  
  50.             Map<String, Object> dataMap = new HashMap<String, Object>();  
  51.             dataMap = getData();  
  52.             //生产word  
  53.             wordUtil.createWord("2.ftl", fileStr+"\\test.doc", dataMap);  
  54.         } catch (Exception e) {  
  55.             e.printStackTrace();  
  56.         }  
  57.     }  
  58.       
  59.     public Map<String, Object> getData() {  
  60.         Map<String, Object> dataMap = new HashMap<String, Object>();  
  61.         WordUtil wordUtil = new WordUtil();  
  62.         String fileStr = wordUtil.saveFile();  
  63.           
  64.         dataMap.put("image", getImageStr(fileStr+"\\test.png"));  
  65.         List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();  
  66.         for (int i = 0; i < 2; i++) {  
  67.             Map<String,Object> map = new HashMap<String,Object>();  
  68.             map.put("xuhao", i);  
  69.             map.put("neirong", "内容"+i);  
  70.             list.add(map);  
  71.               
  72.         }  
  73.         dataMap.put("list", list);  
  74.         dataMap.put("info", "测试");  
  75.         return dataMap;  
  76.     }  
  77.     public String getImageStr(String imgFile) {  
  78.         InputStream in = null;  
  79.         byte[] data = null;  
  80.         try {  
  81.             in = new FileInputStream(imgFile);  
  82.             data = new byte[in.available()];  
  83.             in.read(data);  
  84.             in.close();  
  85.         } catch (IOException e) {  
  86.             e.printStackTrace();  
  87.         }  
  88.         BASE64Encoder encoder = new BASE64Encoder();  
  89.         return encoder.encode(data);  
  90.     }  
  91. }  

5.WordUtil.java

[html] view plaincopy
 
  1. package com.word;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.OutputStreamWriter;  
  11. import java.io.Writer;  
  12. import java.util.Map;  
  13.   
  14. import sun.misc.BASE64Encoder;  
  15. import freemarker.template.Configuration;  
  16. import freemarker.template.Template;  
  17. import freemarker.template.TemplateException;  
  18.   
  19. public class WordUtil {  
  20.     private Configuration configuration = null;  
  21.   
  22.     public WordUtil() {  
  23.         configuration = new Configuration();  
  24.         configuration.setDefaultEncoding("utf-8");  
  25.   
  26.     }  
  27.   
  28.     public void createWord(String templetName, String filePathName, Map<String, Object> dataMap) {  
  29.         configuration.setClassForTemplateLoading(this.getClass(), "/com/word"); // FTL文件所存在的位置  
  30.         Template t = null;  
  31.         try {  
  32.             // 获取模版文件  
  33.             t = configuration.getTemplate(templetName);  
  34.         } catch (IOException e) {  
  35.             e.printStackTrace();  
  36.         }  
  37.         // 生成文件的路径和名称  
  38.         File outFile = new File(filePathName);  
  39.         Writer out = null;  
  40.         try {  
  41.             out = new BufferedWriter(new OutputStreamWriter(  
  42.                     new FileOutputStream(outFile)));  
  43.         } catch (FileNotFoundException e1) {  
  44.             e1.printStackTrace();  
  45.         }  
  46.   
  47.         try {  
  48.             t.process(dataMap, out);  
  49.         } catch (TemplateException e) {  
  50.             e.printStackTrace();  
  51.         } catch (IOException e) {  
  52.             e.printStackTrace();  
  53.         }  
  54.     }  
  55.   
  56.     public String getImageStr(String imgFile) {  
  57.         InputStream in = null;  
  58.         byte[] data = null;  
  59.         try {  
  60.             in = new FileInputStream(imgFile);  
  61.             data = new byte[in.available()];  
  62.             in.read(data);  
  63.             in.close();  
  64.         } catch (IOException e) {  
  65.             e.printStackTrace();  
  66.         }  
  67.         BASE64Encoder encoder = new BASE64Encoder();  
  68.         return encoder.encode(data);  
  69.     }  
  70.     public String saveFile() {  
  71.         String nowpath = System.getProperty("user.dir");  
  72.         String path = nowpath.replace("bin", "webapps");  
  73.         path += "\\"+"TestWeb"+"\\"+"word";  
  74.         File tmp = new File(path);  
  75.         if (!tmp.exists()) {  
  76.             tmp.mkdirs();  
  77.         }  
  78.         return path;  
  79.     }  
  80. }  

6.模版的制作:

1).新建word文档,内容如下图:

2).把word文档另存为Word 2003 XML 文档,打开内容,如下图:

在<w:tr>之前<#list list as list>,在</w:tr>之后加</#list>,如果不循环,不需要加。接在把图片生产的一大串字符改成${image},试情况改此文件的编码。

3).把修改好的xml后缀改为ftl。模版做好,放在指定位置即可。跑完程序后,生产如下word:

大功告成!有什么问题,大家一起讨论!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics