java后端生成word包含echarts图片+表格数据

  • echarts图片后端生成方式
  • echarts包导入
  • echarts核心代码解析
  • 1.创建工具类
  • 2.编写静态工具方法
  • 3.编写具体的功能实现方法
  • 4.组装xData值
  • 5.组装yData值
  • 6.书写需要替换的模板
  • 7.参数组装
  • 8.controller层编写,通过postman测试


echarts图片后端生成方式

由于业务需求产品经理提出需要后端定时生成word报表,不在通过前端页面来进行操作和点击。只需要用户在生成完成的

echarts包导入

<dependency>
        <groupId>com.github.abel533</groupId>
        <artifactId>Echarts</artifactId>
        <version>3.0.0.6</version>
    </dependency>
    **这个包实现了很多的前端echarts界面的功能,即大部分前端API方法,在该包下基本都实现了**

建议:因为这个是通过模板读取变量的方式来实现的,所以我们只需要封装好参数,用插值表达式的方式就可以完美实现该功能,且可以减少后端代码的逻辑,将各种样式和类型的图写在前端html页面上,采用定时关闭和下载的功能。因为这是在服务器上进行生成图片,所以也不用担心用户体验问题,我们支取图片,取完图片后删除即可。

echarts核心代码解析

1.创建工具类

echarts java后台直接生成图片 java图表echarts_echarts

2.编写静态工具方法
/**
 * 导出到指定文件夹,文件名随机
 * @param map
 * @return 返回html路径
 */
public static String exportToHtml(Map<String, Object> map, String url,String lineCode,List<String> stringHtmlList) {
    StringBuffer stringBuffer = new StringBuffer();
    StringBuffer fileName = stringBuffer.append("ECharts-").append(lineCode).append("-").append(System.currentTimeMillis()).append(".html");
    stringHtmlList.add(fileName.toString());
    return exportToHtml(map, fileName.toString(), url,lineCode,stringHtmlList);
}
  /**
 * 获取文件夹路径,如果不存在则创建
 *
 * @param folderPath
 * @return
 */
private static String getFolderPath(String folderPath) {
    File folder = new File(folderPath);
    if (folder.exists() && folder.isFile()) {
        String tempPath = folder.getParent();
        folder = new File(tempPath);
    }
    if (!folder.exists()) {
        folder.mkdirs();
    }
    return folder.getPath();
}
private static List<String> readLines(Map option, String url) {
    InputStream is = null;
    InputStreamReader iReader = null;
    BufferedReader bufferedReader = null;
    List<String> lines = new ArrayList<String>();
    String line;
    try {
        is = OptionUtil.class.getResourceAsStream("/echartsTemplate/"+url);
        iReader = new InputStreamReader(is, "UTF-8");
        bufferedReader = new BufferedReader(iReader);
        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains("##seriesData0##")) {
                line = line.replace("##seriesData0##", GsonUtil.format(option.get("seriesData0")));
            }
            if (line.contains("##seriesData1##")) {
                line = line.replace("##seriesData1##", GsonUtil.format(option.get("seriesData1")));
            }
            if (line.contains("##xData##")) {
                line = line.replace("##xData##", GsonUtil.format(option.get("xData")));
            }
            if (line.contains("##minkY##")) {
                line = line.replace("##minkY##", GsonUtil.format(option.get("minkY")));
            }
            if (line.contains("##minkX##")) {
                line = line.replace("##minkX##", GsonUtil.format(option.get("minkX")));
            }
            if (line.contains("##xAxisName##")) {
                line = line.replace("##xAxisName##", GsonUtil.format(option.get("xAxisName")));
            }
            if (line.contains("##yAxisName##")) {
                line = line.replace("##yAxisName##", GsonUtil.format(option.get("yAxisName")));
            }
            if (line.contains("##textName##")) {
                line = line.replace("##textName##", GsonUtil.format(option.get("textName")));
            }
            lines.add(line);
        }
    } catch (Exception e) {
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }
    return lines;
}
 /**
 * 导出到指定文件
 *
 * @param option
 * @param fileName
 * @return 返回html路径
 */
public static String exportToHtml(Map option, String fileName, String url,String lineCode,List<String> stringHtmlList) {
    File file1 = new File("");
    String path = file1.getAbsolutePath();


// String folderPath = System.getProperty(“java.io.tmpdir”)
if (fileName == null || fileName.length() == 0) {
 return exportToHtml(option, path,lineCode,stringHtmlList);
 }
 Writer writer = null;
 List lines = readLines(option, url);
 //写入文件
 File html = new File(getFolderPath(path +“/echartsHtml” ) +“/” + fileName);
 try {
 writer = new OutputStreamWriter(new FileOutputStream(html), “UTF-8”);
 for (String l : lines) {
 writer.write(l + “\n”);
 }
 } catch (Exception e) {
 } finally {
 if (writer != null) {
 try {
 writer.close();
 } catch (IOException e) {
 //ignore
 }
 }
 }
 //处理
 try {
 return html.getAbsolutePath();
 } catch (Exception e) {
 return null;
 }
 }
 /**
 * 打开浏览器
 *
 * @param url
 * @throws Exception
 */
 public static void browse(String url) throws Exception {
 //获取操作系统的名字
 String osName = System.getProperty(“os.name”, “”);
 log.info(“操作系统的名字:{}”, osName);
 if (osName.startsWith(“Mac OS”)) {
 //苹果的打开方式
 Class fileMgr = Class.forName(“com.apple.eio.FileManager”);
 Method openURL = fileMgr.getDeclaredMethod(“openURL”, new Class[]{String.class});
 openURL.invoke(null, new Object[]{url});
 } else if (osName.startsWith(“Windows”)) {
 //windows的打开方式 默认用预制chrome的浏览器打开。
 File file1 = new File(“”);
 String path = file1.getAbsolutePath();
 url = path + "/echartsHtml/Chrome/Chrome.exe "+url ;
 log.info(“打开浏览器的方式。{}”,url);
 Runtime.getRuntime().exec(url);
 // Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
 } else {
 // Unix or Linux的打开方式
 String[] browsers = {“firefox”, “opera”, “konqueror”, “epiphany”, “mozilla”, “netscape”};
 String browser = null;
 for (int count = 0; count < browsers.length && browser == null; count++) {
 //执行代码,在brower有值后跳出,
 //这里是如果进程创建成功了,==0是表示正常结束。
 if (Runtime.getRuntime().exec(new String[]{“which”, browsers[count]}).waitFor() == 0) {
 browser = browsers[count];
 }
 }
 if (browser == null) {
 throw new Exception(“Could not find web browser”);
 } else {
 //这个值在上面已经成功的得到了一个进程。
 Runtime.getRuntime().exec(new String[]{browser, url});
 }
 }
 }
3.编写具体的功能实现方法

echarts java后台直接生成图片 java图表echarts_java_02


public static void createEchartsHistogram(Map<String, List> resultMap, String dataType, String histogramEchartsTemp, String lineCode) {
 HashMap<String, Object> map = new HashMap<>(6);
 String[] xData = getXdata(resultMap, dataType);
 map.put(“xData”, xData);
 Double[] seriesData0 = getYdata(resultMap, dataType, map,lineCode);
 map.put(“seriesData0”, seriesData0);
 String stairsTemplate1 = OptionUtil.exportToHtml(map, histogramEchartsTemp, lineCode,CreateOperationQualityEchartsUtil.stringHtmlList);
 try {
 Thread.sleep(5000);
 OptionUtil.browse(stairsTemplate1);
 } catch (Exception e) {
}

4.组装xData值

public static String[] getXdata(Map<String, List> resultMap, String dataType) {
 if (dataType.equals(Constants.HORIZONTAL_STABILITY)) {
 List xDataLineCode = resultMap.get(“1”).stream().map(x -> x.get(“lcCode”).toString()).collect(Collectors.toList());
 String[] xData = xDataLineCode.toArray(new String[0]);
 for (int i = 0; i < xDataLineCode.size(); i++) {
 xData[i] = xDataLineCode.get(i);
 }
 return xData;
 }
 if (dataType.equals(Constants.VERTICAL_STABILITY)) {
 List xDataLineCode = resultMap.get(“2”).stream().map(x -> x.get(“lcCode”).toString()).collect(Collectors.toList());
 String[] xData = xDataLineCode.toArray(new String[0]);
 for (int i = 0; i < xDataLineCode.size(); i++) {
 xData[i] = xDataLineCode.get(i);
 }
 return xData;
 }
 if (dataType.equals(Constants.COMFORT)) {
 List xDataLineCode = resultMap.get(“3”).stream().map(x -> x.get(“lcCode”).toString()).collect(Collectors.toList());
 String[] xData = xDataLineCode.toArray(new String[0]);
 for (int i = 0; i < xDataLineCode.size(); i++) {
 xData[i] = xDataLineCode.get(i);
 }
 return xData;
 }
 retur

n null;
}

5.组装yData值
public static Double[] getYdata(Map<String, List<Map>> resultMap, String dataType, HashMap<String, Object> map,String lineCode) {
    map.put("xAxisName", "列车号");
    map.put("yAxisName", "数值");
    if (dataType.equals(Constants.VERTICAL_STABILITY)) {
        List<Double> yData = resultMap.get("2").stream().map(x -> Double.parseDouble(x.get("index").toString()) / 1000).collect(Collectors.toList());
        Double[] ySeriesData = getAyisData(map, yData);
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer append = stringBuffer.append(lineCode).append("-").append("垂向平稳最大值");
        map.put("textName", append.toString());
        double target = 2.00;
        double index = 0.25;
        double sum = target +index;
        Map[] minkY = new Map[3];
        for (int i = 0; i < minkY.length; i++) {
            sum = index + sum;
            HashMap<Object, Object> hashMap1 = new HashMap<>(2);
            hashMap1.put("name", i + 1 + "级");
            hashMap1.put("yAxis",sum);
            minkY[i] = hashMap1;
        }
        map.put("minkY", minkY);
        stringsImageName.add(append.toString());
        return ySeriesData;
    }
    return null;
}
6.书写需要替换的模板

ECharts - Generate By @isea533/abel533

ECharts效果


<div class="push"></div>



作者: @LiNuiCx


7.参数组装

private Map<String, List> getDailyData(String lineCode, List lcCodeList, String lastPgTimeStr) {
 Criteria criteria = new Criteria();
 try {
 criteria.andOperator(Criteria.where(“cyTime”).
 gte(simpleDateFormat.parse(lastPgTimeStr + " 00:00:00"))
 .lte(simpleDateFormat.parse(lastPgTimeStr + " 23:59:59"))
 .and(“lineCode”).is(lineCode)
 .and(“lcCode”).in(lcCodeList));
 } catch (ParseException e) {
 e.printStackTrace();
 }
 Aggregation aggregation = Aggregation.newAggregation(
 Aggregation.match(criteria)
 );
 List mappedResults = mongoTemplate.aggregate(aggregation, YZD_QUA_SHOW_DAY, Map.class).getMappedResults();
 Map<String, List> resultMap = mappedResults.stream().collect(Collectors.groupingBy(map -> map.get(“dataType”).toString() + “-” + map.get(“lcCode”).toString()));
 Map<String, List> reMap = new HashMap<>();
 for (String type_lcCode : resultMap.keySet()) {
 String[] arr = type_lcCode.split(“-”);
 Map maxMap = resultMap.get(type_lcCode).stream().max((map1, map2) -> {
 return Integer.valueOf(map1.getOrDefault(“index”, 0) + “”) - Integer.valueOf(map2.getOrDefault(“index”, 0) + “”);
 }).get();
 if (reMap.get(arr[0]) != null) {
 reMap.get(arr[0]).add(maxMap);
 } else {
 ArrayList list = new ArrayList<>();
 list.add(maxMap);
 reMap.put(arr[0], list);
 }
 }
 return reMap;
 }

8.controller层编写,通过postman测试

@GetMapping("/dailyQuaShow")
public ResponseJson dailyQuaShow(@RequestParam("lineCode") String lineCode) {
    List<Object> runningQuaShowData = runningQuaShowService.getDailyQuaShow(lineCode);
    return DataUtils.sucessObj(runningQuaShowData);
}

echarts java后台直接生成图片 java图表echarts_List_03


默认下载地址

echarts java后台直接生成图片 java图表echarts_echarts_04


接下用路径去找到图片,再插入到word文档即可

echarts java后台直接生成图片 java图表echarts_echarts_05

以上是生成echarts图片的方法,数据库采用的是mongodb数据库。代码仅供学习使用,商用侵权必究。下次在更新生成word代码方法