你們知道,“當任務數超過線程池的核心線程數時,如何讓它不進入隊列,而是直接啟用最大線程數”嗎? 大家好,我是Mic,一個工作了14年的Java程式員。 剛剛這個問題是一個工作5年的粉絲最近去某互聯網公司面試遇到的。 關於這個問題,我把高手的回答整理到了一個15W字的面試文檔裡面。 大家可以私信我領取 ...
需求是導出word,裡面有數據統計圖表。
要從後端直接導出圖表的話,思路是這樣的:
先通過echarts生成圖片,通過phantomjs 截圖,將圖片暫存在本地,再將圖片轉換成base64,然後放入word。
phantomjs 是一個基於js的webkit內核無頭瀏覽器 也就是沒有顯示界面的瀏覽器。
一、準備word模板,轉換成xml,需要填入數據的地方用${欄位},需要天出圖片的地方可以先隨便一張用圖片替代,方便之後找到圖片插入位置。這裡就不多說了
二、準備環境、依賴
1、準備js,需要用到的,放在同一個文件夾下麵。自己更改echarts-convert.js的路徑
echarts.min.js 和jquery.js 去官網下載
echarts-convert.js的內容如下:
(function () { var system = require('system'); var fs = require('fs'); var config = { // define the location of js files //這樣寫要求這三個js在同一個文件夾下 JQUERY: 'jquery-3.5.1.min.js', //ESL: 'esl.js', ECHARTS: 'echarts.min.js', // default container width and height DEFAULT_WIDTH: '400', DEFAULT_HEIGHT: '600' }, parseParams, render, pick, usage; usage = function () { console.log("\nUsage: phantomjs echarts-convert.js -options options -outfile filename -width width -height height" + "OR" + "Usage: phantomjs echarts-convert.js -infile URL -outfile filename -width width -height height\n"); }; pick = function () { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i += 1) { arg = args[i]; if (arg !== undefined && arg !== null && arg !== 'null' && arg != '0') { return arg; } } }; parseParams = function () { var map = {}, i, key; if (system.args.length < 2) { usage(); phantom.exit(); } for (i = 0; i < system.args.length; i += 1) { if (system.args[i].charAt(0) === '-') { key = system.args[i].substr(1, i.length); if (key === 'infile') { // get string from file // force translate the key from infile to options. key = 'options'; try { map[key] = fs.read(system.args[i + 1]).replace(/^\s+/, ''); } catch (e) { console.log('Error: cannot find file, ' + system.args[i + 1]); phantom.exit(); } } else { map[key] = system.args[i + 1].replace(/^\s+/, ''); } } } return map; }; render = function (params) { var page = require('webpage').create(), createChart; var bodyMale = config.SVG_MALE; page.onConsoleMessage = function (msg) { console.log(msg); }; page.onAlert = function (msg) { console.log(msg); }; createChart = function (inputOption, width, height,config) { var counter = 0; function decrementImgCounter() { counter -= 1; if (counter < 1) { console.log(messages.imagesLoaded); } } function loadScript(varStr, codeStr) { var script = $('<script>').attr('type', 'text/javascript'); script.html('var ' + varStr + ' = ' + codeStr); document.getElementsByTagName("head")[0].appendChild(script[0]); if (window[varStr] !== undefined) { console.log('Echarts.' + varStr + ' has been parsed'); } } function loadImages() { var images = $('image'), i, img; if (images.length > 0) { counter = images.length; for (i = 0; i < images.length; i += 1) { img = new Image(); img.onload = img.onerror = decrementImgCounter; img.src = images[i].getAttribute('href'); } } else { console.log('The images have been loaded'); } } // load opitons if (inputOption != 'undefined') { // parse the options loadScript('options', inputOption); // disable the animation options.animation = false; } // we render the image, so we need set background to white. $(document.body).css('backgroundColor', 'white'); var container = $("<div>").appendTo(document.body); container.attr('id', 'container'); container.css({ width: width, height: height }); // render the chart var myChart = echarts.init(container[0]); myChart.setOption(options); // load images loadImages(); return myChart.getDataURL(); }; // parse the params page.open("about:blank", function (status) { // inject the dependency js page.injectJs(config.ESL); page.injectJs(config.JQUERY); page.injectJs(config.ECHARTS); var width = pick(params.width, config.DEFAULT_WIDTH); var height = pick(params.height, config.DEFAULT_HEIGHT); // create the chart var base64 = page.evaluate(createChart, params.options, width, height,config); fs.write("base64.txt",base64); // define the clip-rectangle page.clipRect = { top: 0, left: 0, width: width, height: height }; // render the image page.render(params.outfile); console.log('render complete:' + params.outfile); // exit phantom.exit(); }); }; // get the args var params = parseParams(); // validate the params if (params.options === undefined || params.options.length === 0) { console.log("ERROR: No options or infile found."); usage(); phantom.exit(); } // set the default out file if (params.outfile === undefined) { var tmpDir = fs.workingDirectory + '/tmp'; // exists tmpDir and is it writable? if (!fs.exists(tmpDir)) { try { fs.makeDirectory(tmpDir); } catch (e) { console.log('ERROR: Cannot make tmp directory'); } } params.outfile = tmpDir + "/" + new Date().getTime() + ".png"; } // render the image render(params); }());
2、安裝phantomjs
網站:https://phantomjs.org/download.html
選擇合適的版本,我下載的是windows的,下載解壓
配置環境變數:
然後測試是否安裝成功,在命令行 輸入:phantomjs -- version
出現版本就表示安裝成功了。
3、構建echarts數據,就是option
可以看原文檔:https://gitee.com/free/ECharts#https://gitee.com/link?target=http%3A%2F%2Fblog.csdn.net%2Fisea533%2Farticle%2Fdetails%2F43225717
<dependency> <groupId>com.github.abel533</groupId> <artifactId>ECharts</artifactId> <version>3.0.0.6</version> </dependency>
三、生成echarts圖表
1、構建echarts 的數據option
/** * 構建柱狀圖 * @param cate x軸數據 * @param enterpriseCnt 數據 * @return */ private static String getOption(List<String> cate, List<Integer> enterpriseCnt){ GsonOption option = new GsonOption(); option.title().setText("測試點位數圖片"); // 標題 // 設置圖例 option.legend().data("點位數").x("center"); Bar bar = new Bar(); // x軸 CategoryAxis category = new CategoryAxis(); category.data(cate.toArray()); //y 軸 ValueAxis valueAxis = new ValueAxis(); bar.data().addAll(enterpriseCnt); // 數據 option.xAxis(category); //x軸 option.yAxis(valueAxis); //y軸 option.series(bar);// 多條柱子放多個bar就行 String optionStr = option.toString().replace(" ", ""); log.info(optionStr); return optionStr; }
2、生成echarts圖片
public static String generateEChart(String option, String filepath, String fileName) { String dataPath = writeOptionToFile(option, filepath); // 將option 數據寫磁碟上用文件保存 String path = filepath + fileName+".png"; //生成圖片路徑 try { String JSpath = "D:\\data\\tmp\\echarts-convert.js"; String cmd = "phantomjs " + JSpath + " -infile " + dataPath + " -outfile " + path; log.info(cmd); Process process = Runtime.getRuntime().exec(cmd); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line = ""; while ((line = input.readLine()) != null) { log.info(line); } input.close(); // 刪除json數據 File jsonFile = new File(dataPath); jsonFile.delete(); } catch (IOException e) { e.printStackTrace(); } return path; }
public static String writeOptionToFile(String options, String filepath) { String dataPath = filepath +"echart.json"; try { File writename = new File(dataPath); if (!writename.getParentFile().exists()) { //文件目錄不存在,則先創建,不然會報錯 writename.getParentFile().mkdirs(); } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writename), "UTF-8")); out.write(options); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } return dataPath; }
先測試一哈:
這個時候在文件夾下可以看到圖片啦:
四、導出word
準備好數據,圖片需要base64編碼的,將之前生成的echart圖片讀入轉base64
public static String imageToBase64(String imgPath) { InputStream in = null; byte[] data = null; try { in = new FileInputStream(imgPath); data = new byte[in.available()]; in.read(data); in.close(); } catch(Exception ex) { ex.printStackTrace(); } Base64Encoder encoder = new Base64Encoder(); return encoder.encode(data); }
然後就是正常word的導出了