java生成echarts图片并且下载到本地

echarts图片后端生成方式

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

echarts包导入

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

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

echarts核心代码解析

1.创建工具类

!](https://img-blog.csdnimg.cn/7b38813829584706913407b13d43ed29.png)

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.编写具体的功能实现方法

在这里插入图片描述
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;
}
return 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>
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);
}

在这里插入图片描述
默认下载地址
在这里插入图片描述
接下用路径去找到图片,再插入到word文档即可
在这里插入图片描述

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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要使用Java生成echarts图片,可以使用Java的开源库echarts-java。该库提供了Javaecharts的集成,可以通过Java代码生成echarts图表,并将其保存为图片。 首先,需要在项目中导入echarts-java的依赖,可以使用Maven或Gradle进行管理。 在代码中,首先创建一个echarts对象,通过设置不同的属性来配置图表的内容和样式。例如,可以设置图表类型、标题、横纵坐标等。 然后,可以创建一个echarts图片生成器对象,将echarts对象作为参数传递给生成器。可以设置生成图片的格式、大小和保存路径等。 最后,调用生成器的generate方法,即可根据echarts对象生成相应的图片并保存。 以下是一个简单的示例代码: ```java import com.github.abel533.echarts.Option; import com.github.abel533.echarts.json.GsonOption; import com.github.abel533.echarts.utils.EchartsUtils; import com.github.abel533.echarts.util.EnhancedOption; import com.github.abel533.echarts.image.ZEChartsConfig; import com.github.abel533.echarts.image.ZEChartsRenderTool; public class EchartsImageGenerator { public static void main(String[] args) { // 创建echarts对象 EnhancedOption option = new EnhancedOption(); option.title().text("示例图表"); option.legend().data("A", "B"); option.xAxis().data("1月", "2月", "3月", "4月", "5月"); option.yAxis().name("销量"); // 添加数据系列 option.series("A", "bar", new Integer[]{10, 20, 30, 40, 50}); option.series("B", "line", new Integer[]{5, 10, 15, 20, 25}); // 创建echarts图片生成器对象 ZEChartsConfig config = new ZEChartsConfig(); config.setRenderTool(ZEChartsConfig.getRenderToolOrInstance()); config.setImagePath("data:image/png;base64"); config.setCharsetName("UTF-8"); ZEChartsRenderTool renderTool = new ZEChartsRenderTool(); renderTool.setConfig(config); // 生成图片并保存 String outputPath = "path/to/output/image.png"; renderTool.renderToPath(EchartsUtils.getInstanceFromOption(option, GsonOption.class), outputPath); } } ``` 通过上述代码,我们可以利用Java调用echarts-java库来生成echarts图片。可以根据实际需求,使用不同的图表类型和数据来定制生成图片
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值