ITeye博客

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

adminjun · 2016-01-29 09:38 · echarts · Web前端 · Markdown

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

4.SaveImage.java

[html] view plaincopy

 

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

5.WordUtil.java

[html] view plaincopy

 

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

6.模版的制作:

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

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

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

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

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。