日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java后端使用freemarker生成echarts图表word

發布時間:2023/12/10 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java后端使用freemarker生成echarts图表word 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

項目結構

package com.example.demo.月報;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;@RestController @RequestMapping(value = "/echarts") public class EchartsController {@AutowiredEchartsService echartsService;// @ApiOperation(value = "下載統計月報", notes = "")@GetMapping(value = "getFile")public void getFile(HttpServletResponse response) throws Exception {echartsService.getFile(null, response);}} package com.example.demo.月報;import javax.servlet.http.HttpServletResponse;public interface EchartsService {void getFile( StatisticsTableDto statisticsTableDto, HttpServletResponse response) throws Exception; } package com.example.demo.月報;import com.example.demo.zip.FileUtil; import org.springframework.stereotype.Service;import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Base64; import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID;@Service public class EchartsServiceImpl implements EchartsService {private static final String JSpath = System.getProperty("user.dir") + File.separator+"src\\main\\resources\\templates\\echarts-convert.js";@Overridepublic void getFile( StatisticsTableDto statisticsTableDto, HttpServletResponse response) throws Exception { // statisticsTableDto = StatisticsUtil.getComplaintTime(statisticsTableDto);ServletOutputStream out = response.getOutputStream();String options = "{\"title\":{\"text\":\"銷售圖\",\"subtext\":\"銷售統計\",\"x\":\"CENTER\"},\"toolbox\": {\"feature\": {\"saveAsImage\": {\"show\": true,}}},\"tooltip\": {\"show\": true},\"legend\": {\"data\":[\"直接訪問\",\"郵件營銷\",\"聯盟廣告\",\"視頻廣告\",\"搜索引擎\"]}, \"series\":[{\"name\":\"訪問來源\",\"type\":\"pie\",\"radius\": '55%',\"center\": ['50%', '60%'],\"data\":[{\"value\":335, \"name\":\"直接訪問\"},{\"value\":310, \"name\":\"郵件營銷\"},{\"value\":234, \"name\":\"聯盟廣告\"},{\"value\":135, \"name\":\"視頻廣告\"},{\"value\":1548, \"name\":\"搜索引擎\"}]}]}";String picPath = generateEChart(options);String images1 = encryptToBase64(picPath);ExportMyWord emw = new ExportMyWord();String fileName = File.separator + UUID.randomUUID()+ ".doc";Map<String, Object> map = new LinkedHashMap<>(); // String time = statisticsTableDto.getComplaintTimeStart() + "至" + statisticsTableDto.getComplaintTimeEnd();map.put("time", "測試");map.put("image1", images1);map.put("image2", images1);map.put("image3", images1);emw.createWord(map, "統計表.ftl", fileName);try {response.setContentType("application/octet-stream;charset=utf-8");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));InputStream input = null;File file = null;try {file = new File(fileName);input = new FileInputStream(file);byte[] bytes = new byte[1024 * 50];int len = -1;//解釋這個fis.read(bytes)的意思:從讀取流"讀取數組長度"的數據(打印len可知),并放入數組while ((len = input.read(bytes, 0, 1024)) != -1) {//雖然數組長度的*5,但是這里我們設置了1024所以每次輸出1024//因為每次得到的是新的數組,所以每次都是新數組的"0-len"out.write(bytes, 0, len);}} finally {if (input != null) {input.close();}if (file != null) {FileUtil.deleteFile(file);}}response.flushBuffer();} catch (IOException e) {e.printStackTrace();} finally {if (out != null) {out.close();}}}/** 主程序*/private static String generateEChart(String options) {String dataPath = writeFile(options);String fileName = UUID.randomUUID().toString() + ".png";String path = File.separator + fileName;try {File file = new File(path); //文件路徑if (!file.exists()) {File dir = new File(file.getParent());dir.mkdirs();file.createNewFile();}String sysName = System.getProperty("os.name");//絕對路徑String cmd;if (sysName.contains("Windows")){cmd = "D:\\PhantomJs\\phantomjs-2.1.1-windows\\bin\\phantomjs " + JSpath + " -infile " + dataPath + " -outfile " + path;//生成命令行}else if (sysName.contains("Linux")){cmd = "phantomjs " + JSpath + " -infile " + dataPath + " -outfile " + path;}else {return "暫不支持本機的運行系統";}Process process = Runtime.getRuntime().exec(cmd);BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));String line = "";while ((line = input.readLine()) != null) {}input.close();} catch (IOException e) {e.printStackTrace();} finally {FileUtil.clearFiles(dataPath);}return path;}/*** options生成文件存儲*/private static String writeFile(String options) {String dataPath = File.separator + UUID.randomUUID().toString().substring(0, 8) + ".json";try {/* option寫入文本文件 用于執行命令*/File writename = new File(dataPath);if (!writename.exists()) {File dir = new File(writename.getParent());dir.mkdirs();writename.createNewFile(); //}BufferedWriter out = new BufferedWriter(new FileWriter(writename));out.write(options);out.flush(); // 把緩存區內容壓入文件out.close(); // 最后關閉文件} catch (IOException e) {e.printStackTrace();}return dataPath;}private static String encryptToBase64(String filePath) {if (filePath == null) {return null;}try {byte[] b = Files.readAllBytes(Paths.get(filePath));return Base64.getEncoder().encodeToString(b);} catch (IOException e) {e.printStackTrace();}finally {FileUtil.clearFiles(filePath);}return null;}} package com.example.demo.月報;import freemarker.core.ParseException; import freemarker.log.Logger; import freemarker.template.Configuration; import freemarker.template.MalformedTemplateNameException; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import freemarker.template.TemplateNotFoundException;import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Map;public class ExportMyWord {private Logger log = Logger.getLogger(ExportMyWord.class.toString());private Configuration config = null;public ExportMyWord() {config = new Configuration(Configuration.VERSION_2_3_28);config.setDefaultEncoding("utf-8");}/*** FreeMarker生成Word** @param dataMap 數據* @param templateName 目標名* @param saveFilePath 保存文件路徑的全路徑名(路徑+文件名)*/public void createWord(Map<String, Object> dataMap, String templateName, String saveFilePath) {//加載模板(路徑)數據config.setClassForTemplateLoading(this.getClass(), "/templates/");//設置異常處理器 這樣的話 即使沒有屬性也不會出錯 如:${list.name}...不會報錯config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);Template template = null;if (templateName.endsWith(".ftl")) {templateName = templateName.substring(0, templateName.indexOf(".ftl"));}try {template = config.getTemplate(templateName + ".ftl");} catch (TemplateNotFoundException e) {log.error("模板文件未找到", e);e.printStackTrace();} catch (MalformedTemplateNameException e) {log.error("模板類型不正確", e);e.printStackTrace();} catch (ParseException e) {log.error("解析模板出錯,請檢查模板格式", e);e.printStackTrace();} catch (IOException e) {log.error("IO讀取失敗", e);e.printStackTrace();}File outFile = new File(saveFilePath);if (!outFile.getParentFile().exists()) {outFile.getParentFile().mkdirs();}Writer out = null;FileOutputStream fos = null;try {fos = new FileOutputStream(outFile);} catch (FileNotFoundException e) {log.error("輸出文件時未找到文件", e);e.printStackTrace();}out = new BufferedWriter(new OutputStreamWriter(fos));//將模板中的預先的代碼替換為數據try {template.process(dataMap, out);} catch (TemplateException e) {log.error("填充模板時異常", e);e.printStackTrace();} catch (IOException e) {log.error("IO讀取時異常", e);e.printStackTrace();}log.info("由模板文件:" + templateName + ".ftl" + " 生成文件 :" + saveFilePath + " 成功!!");try {if (fos != null) {fos.close();}out.close();//web項目不可關閉} catch (Exception e) {log.error("關閉Write對象出錯", e);e.printStackTrace();}}}

總結

以上是生活随笔為你收集整理的java后端使用freemarker生成echarts图表word的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。