当前位置:   article > 正文

easypoi 导出word并插入echart图片和文件_apipost导出word

apipost导出word
  1. 一 pom 文件引入:
  2. <!-- 目前的版本对应 poi 4.1.2 和 xmlbeans 3.1.0 , poi 3.17 和 xmlbeans 2.6.0 -->
  3. <dependency>
  4. <groupId>org.apache.poi</groupId>
  5. <artifactId>poi</artifactId>
  6. <version>4.1.2</version>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.apache.poi</groupId>
  10. <artifactId>poi-ooxml</artifactId>
  11. <version>4.1.2</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.apache.xmlbeans</groupId>
  15. <artifactId>xmlbeans</artifactId>
  16. <version>3.1.0</version>
  17. </dependency>
  18. <!-- easypoi导出word -->
  19. <dependency>
  20. <groupId>cn.afterturn</groupId>
  21. <artifactId>easypoi-spring-boot-starter</artifactId>
  22. <version>4.4.0</version>
  23. </dependency>
  24. 二 DownloadReportController 层
  25. /**
  26. *下载word
  27. * @param response
  28. * @throws Exception
  29. */
  30. @ApiOperation("下载word")
  31. @PostMapping("/exportToWord")
  32. public void exportToWord(HttpServletResponse response, @RequestBody DownloadReportSearchVo downloadReportSearchVo) {
  33. String secCode = SecurityContextHolder.getUserStockCode();
  34. HengShenCompanyInfoDto companyInfoDto = remoteBasicService.getCompanyInfoByCode(secCode).getData();
  35. String companyReferred = companyInfoDto.getCompanyReferred();
  36. String day = DateUtil.format(new Date(),"yyyyMMdd");
  37. String wordFileName = companyReferred+"("+secCode+")"+"市值诊断报告_"+day+".docx";
  38. try {
  39. downloadReportSearchVo.setSecCode(secCode);
  40. Map<String, Object> wordInitDataMaps = downloadReportService.exportToWord(downloadReportSearchVo);
  41. // 前端调用下面初始化word数据方法,下载时候从缓存取word map类型替换数据;
  42. // Map<String, Object> wordInitDataMaps = redisService.getCacheMap(DOWNLOADREPORT_WORDDATA+secCode);
  43. //读取模板 并 一次性提交maps里要替换的文字和图片内容,然后导出word;
  44. XWPFDocument word = null;
  45. try {
  46. word = WordExportUtil.exportWord07(phantomjsRoot+"/市值诊断报告_YYYYMMDD.docx", wordInitDataMaps);
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(wordFileName,"UTF-8"));
  51. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  52. ServletOutputStream outputStream = response.getOutputStream();
  53. word.write(outputStream);
  54. outputStream.close();
  55. word.close();
  56. } catch (UnsupportedEncodingException e) {
  57. e.printStackTrace();
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. 三 service 层
  63. @Override
  64. public Map<String, Object> exportToWord(DownloadReportSearchVo downloadReportSearchVo) {
  65. String secCode = downloadReportSearchVo.getSecCode();
  66. Map<String, Object> maps=new HashMap<>();
  67. // 1-1 诊断结果>市值表现
  68. // 1-2 诊断结果>流动性情况
  69. //获取本模块4个echart图形数据和文字描述
  70. LiquidityAnalysisVO liquidityAnalysisVO = liquiditySituationService.analysisResult(secCode);
  71. //生成echart图片,并替换图片和文字
  72. maps = liquiditySituationService.analysisResultToEchartImg(liquidityAnalysisVO,maps);
  73. // 1-3 诊断结果>股东结构分析
  74. //2-1 A股市值表现>市值对比
  75. //2-2 A股市值表现>估值对比
  76. //2-3 A股市值表现>股价对比
  77. return maps;
  78. }
  79. /**
  80. * 根据原图表数据,封装echart json option 格式,并生成echart图片
  81. *
  82. * @param liquidityAnalysisVO
  83. */
  84. @Override
  85. public Map<String, Object> analysisResultToEchartImg(LiquidityAnalysisVO liquidityAnalysisVO, Map<String, Object> maps) {
  86. List<String> colorList = Arrays.asList("rgb(52,113,219)", "rgb(46,167,224)", "rgb(16,197,121)", "rgb(248,180,0)");
  87. String suggest = liquidityAnalysisVO.getSuggest();
  88. String yearAvgSuggest = liquidityAnalysisVO.getYearAvgSuggest();
  89. // 1 第一张echart图 生成echart option
  90. //换手率 替换第一张图片和文字
  91. List<OverviewVO> listYearAvgAnalysis = liquidityAnalysisVO.getYearAvgAnalysis();
  92. List<String> indexkeyYearAvgAnalysis = listYearAvgAnalysis.stream().map(overviewVO -> overviewVO.getIndexKey()).collect(Collectors.toList());
  93. List<BigDecimal> indexValueYearAvgAnalysis = listYearAvgAnalysis.stream().map(overviewVO -> overviewVO.getIndexValue()).collect(Collectors.toList());
  94. maps.put(DownloadReportEnum.DIAGNOSTIC_RESULT_FLOW_SUGGEST.getName(), suggest);
  95. maps.put(DownloadReportEnum.DIAGNOSTIC_RESULT_FLOW_1_YEARAVGSUGGEST.getName(), yearAvgSuggest.replaceAll("<span>", "").replaceAll("</span>", ""));
  96. String option = "{\n" +
  97. " title: {\n" +
  98. " text: '换手率'\n" +
  99. " },\n" +
  100. " tooltip: {\n" +
  101. " trigger: 'axis',\n" +
  102. " axisPointer: {\n" +
  103. " type: 'shadow'\n" +
  104. " }\n" +
  105. " },\n" +
  106. " legend: {},\n" +
  107. " grid: {\n" +
  108. " left: '3%',\n" +
  109. " right: '4%',\n" +
  110. " bottom: '3%',\n" +
  111. " containLabel: true\n" +
  112. " },\n" +
  113. " xAxis: {\n" +
  114. " type: 'value',\n" +
  115. " boundaryGap: [0, 0.01]\n" +
  116. " },\n" +
  117. " yAxis: {\n" +
  118. " type: 'category',\n" +
  119. " data: ['" + StringUtils.join(indexkeyYearAvgAnalysis, "','") + "'] \n" +
  120. " },\n" +
  121. " series: [\n" +
  122. " {\n" +
  123. " barWidth:30, " +
  124. " name: '当年度年平均换手率(%)',\n" +
  125. " type: 'bar',\n" +
  126. " data: [ \n ";
  127. for (int i = 0; i < indexValueYearAvgAnalysis.size(); i++) {
  128. BigDecimal value = indexValueYearAvgAnalysis.get(i);
  129. String color = colorList.get(i);
  130. option += " { " +
  131. "value: " + numberUtils.formatToBigDecimal(value) + ", " +
  132. "itemStyle: { " +
  133. "color: '" + color + "' " +
  134. "} " +
  135. "}, ";
  136. }
  137. option += " ]} \n" +
  138. " ]\n" +
  139. "};\n";
  140. String echartImgPath1 = eChartImgService.generateEChartImg(option);
  141. // 2 生成要代替word里图像英文单词字符串
  142. ImageEntity imageEntity = new ImageEntity();
  143. imageEntity.setUrl(echartImgPath1);
  144. imageEntity.setWidth(500);
  145. imageEntity.setHeight(300); // 这里的宽高一定要设置,不然图片出不来
  146. maps.put(DownloadReportEnum.DIAGNOSTIC_RESULT_FLOW_1_IMG1.getName(), imageEntity);//替换图片
  147. }
  148. 四: phantomjs 插件生成echart 图片
  149. package com.realize.market.value.service.impl;
  150. import com.realize.market.value.service.IEChartImgService;
  151. import lombok.extern.slf4j.Slf4j;
  152. import org.apache.commons.lang3.StringUtils;
  153. import org.slf4j.Logger;
  154. import org.slf4j.LoggerFactory;
  155. import org.springframework.beans.factory.annotation.Value;
  156. import org.springframework.stereotype.Service;
  157. import java.io.*;
  158. import java.util.UUID;
  159. @Service
  160. @Slf4j
  161. public class EChartImgServiceImpl implements IEChartImgService {
  162. private static final Logger logger = LoggerFactory.getLogger(EChartImgServiceImpl.class);
  163. private static String phantomjsRoot;
  164. private static String phantomjsWindowPath;
  165. private static String phantomjsLinuxPath;
  166. private static String JSpath;
  167. @Value("${phantomjs.root}")
  168. public void setSender(String phantomjs) {
  169. phantomjsRoot = phantomjs;
  170. phantomjsWindowPath=phantomjsRoot+"/phantomjs-2.1.1-windows/bin/phantomjs.exe";
  171. phantomjsLinuxPath=phantomjsRoot+"/phantomjs-2.1.1-linux-x86_64/bin/phantomjs";
  172. JSpath=phantomjsRoot+"/echarts-convert/echarts-convert1.js";
  173. }
  174. @Override
  175. public String generateEChartImg(String options) {
  176. // 1此处可根据操作系统获取对应phantomjs文件路径(phantomjs.exe对应Windows,phantomjs对应Linux)
  177. String phantomjsPath = "";
  178. String os = System.getProperty("os.name").toLowerCase();
  179. if (os.contains("windows")) {
  180. phantomjsPath = phantomjsWindowPath;
  181. }else{
  182. phantomjsPath = phantomjsLinuxPath;
  183. }
  184. // 2根据各模块传递过来的 echart json, 生成服务器本地 echart json文件
  185. //String inputDataPath = writeLocalJsonFile(options);
  186. String filename = UUID.randomUUID().toString().replaceAll("-","");
  187. String inputDataPath=phantomjsRoot+"/data/"+filename+".json";
  188. try {
  189. /* 写入json文件 */
  190. File writename = new File(inputDataPath); // 相对路径,如果没有则要建立一个新的output.json文件
  191. if (!writename.exists()) { //文件不存在则创建文件,先创建目录
  192. File dir = new File(writename.getParent());
  193. dir.mkdirs();
  194. writename.createNewFile(); // 创建新文件
  195. }
  196. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writename),"utf-8"));
  197. out.write(options); // \r\n即为换行
  198. out.flush(); // 把缓存区内容压入文件
  199. out.close(); // 最后记得关闭文件
  200. } catch (IOException e) {
  201. e.printStackTrace();
  202. }
  203. // 3读取本地echart json 格式文件生成 echart 图片
  204. String outfilePath = phantomjsRoot+"/Echart/" +filename+ ".png";
  205. try {
  206. File file = new File(outfilePath); //文件路径(路径+文件名)
  207. if (!file.exists()) { //文件不存在则创建文件,先创建目录
  208. File dir = new File(file.getParent());
  209. dir.mkdirs();
  210. file.createNewFile();
  211. }
  212. // 执行 phantomjs 插件命令,输入json ,输出echart图片生成;
  213. String cmd = phantomjsPath+" " + JSpath + " -infile " + inputDataPath + " -outfile " + outfilePath;
  214. excuteCMDBatFile(cmd,filename);
  215. //Process process = Runtime.getRuntime().exec(cmd);
  216. //BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
  217. //input.close();
  218. } catch (IOException e) {
  219. e.printStackTrace();
  220. }finally{
  221. return outfilePath;
  222. }
  223. }
  224. /**
  225. * 1.将执行的命名写入到sh/cmd文件中,没有用 Runtime 直接执行命令,避免系统阻塞卡顿
  226. * @param exportFile
  227. * @param content
  228. * @return
  229. */
  230. public boolean writeFile(File exportFile, String content) {
  231. if (exportFile == null || StringUtils.isEmpty(content)) {
  232. return false;
  233. }
  234. if (!exportFile.exists()) {
  235. try {
  236. exportFile.getParentFile().mkdirs();
  237. exportFile.createNewFile();
  238. } catch (IOException e) {
  239. e.printStackTrace();
  240. logger.error("create local json file exception: " + e.getMessage());
  241. return false;
  242. }
  243. }
  244. BufferedWriter bufferedWriter = null;
  245. try {
  246. FileOutputStream os = new FileOutputStream(exportFile);
  247. FileDescriptor fd = os.getFD();
  248. bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
  249. bufferedWriter.write(content);
  250. //Flush the data from the streams and writes into system buffers
  251. //The data may or may not be written to disk.
  252. bufferedWriter.flush();
  253. //block until the system buffers have been written to disk.
  254. //After this method returns, the data is guaranteed to have
  255. //been written to disk.
  256. fd.sync();
  257. //设置文件权限
  258. exportFile.setExecutable(true);
  259. exportFile.setReadable(true);
  260. exportFile.setWritable(true);
  261. } catch (UnsupportedEncodingException e) {
  262. logger.error("saveDBData#catch an UnsupportedEncodingException (" + e.getMessage() + ")");
  263. return false;
  264. } catch (FileNotFoundException e) {
  265. logger.error("saveDBData#catch an FileNotFoundException (" + e.getMessage() + ")");
  266. return false;
  267. } catch (IOException e) {
  268. logger.error("saveDBData#catch an IOException (" + e.getMessage() + ")");
  269. return false;
  270. } catch (Exception e) {
  271. logger.error("saveDBData#catch an exception (" + e.getMessage() + ")");
  272. return false;
  273. } finally {
  274. try {
  275. if (bufferedWriter != null) {
  276. bufferedWriter.close();
  277. bufferedWriter = null;
  278. }
  279. } catch (IOException e) {
  280. logger.error("writeJsonToFile#catch an exception (" + e.getMessage() + ")");
  281. }
  282. }
  283. return true;
  284. }
  285. //2.执行命令 phantomjs 插件生成echart 图片
  286. public boolean excuteCMDBatFile(String cmd,String filename) {
  287. String os = System.getProperty("os.name").toLowerCase();
  288. String batFilePath="";
  289. if (os.contains("windows")) {
  290. batFilePath = phantomjsRoot+"/data/"+filename+".bat";
  291. }else{
  292. batFilePath = phantomjsRoot+"/data/"+filename+".sh";
  293. }
  294. final String METHOD_NAME = "excuteCMDBatFile#";
  295. boolean result = true;
  296. Process p;
  297. File batFile = new File(batFilePath);
  298. //System.out.println(batFile.getAbsolutePath());
  299. //命令写入bat文件
  300. boolean isSuccess = writeFile(batFile, cmd);
  301. if(!isSuccess) {
  302. logger.error(METHOD_NAME + "write cmd to File failed.");
  303. return false;
  304. }
  305. logger.info("cmd path:" + batFilePath);
  306. try {
  307. //执行命令 bat文件
  308. p = Runtime.getRuntime().exec(batFilePath);
  309. InputStream fis = p.getErrorStream();//p.getInputStream();
  310. InputStreamReader isr = new InputStreamReader(fis, System.getProperty("file.encoding"));
  311. BufferedReader br = new BufferedReader(isr);
  312. String line = null;
  313. StringBuilder builder = new StringBuilder();
  314. while ((line = br.readLine()) != null) {
  315. builder.append(line);
  316. }
  317. p.waitFor();
  318. int i = p.exitValue();
  319. logger.info(METHOD_NAME + "exitValue = " + i);
  320. if (i != 0) {
  321. result = false;
  322. logger.error(METHOD_NAME + "excute cmd failed, [result = " + result + ", error message = " + builder.toString() + "]");
  323. //System.out.println(METHOD_NAME + "excute cmd failed, [result = " + result + ", error message = " + builder.toString() + "]");
  324. }else {
  325. // logger.debug(METHOD_NAME + "excute cmd result = " + result);
  326. System.out.println(METHOD_NAME + "result = " + result);
  327. }
  328. } catch (Exception e) {
  329. result = false;
  330. e.printStackTrace();
  331. logger.error(METHOD_NAME + "fail to excute bat File [ErrMsg=" + e.getMessage() + "]");
  332. }
  333. return result;
  334. }
  335. /*public static void main(String[] args) {
  336. //String cmd="F:/usr/local/plugin/phantomjs-2.1.1-windows/bin/phantomjs.exe F:/usr/local/plugin/echarts-convert/echarts-convert1.js -infile F:/usr/local/plugin/data/37da9189.json -outfile F:/usr/local/plugin/Echart/37da9189-1.png";
  337. String cmd="/usr/local/plugin/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/plugin/echarts-convert/echarts-convert1.js -infile /usr/local/plugin/data/37da9189.json -outfile /usr/local/plugin/Echart/37da9189-1.png";
  338. excuteCMDBatFile(cmd);
  339. }*/
  340. }

插件包含内容:

1 phantomjs-2.1.1-windows 执行转化图片命令

2 echarts-convert js生成ecahrt 图片

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/540298
推荐阅读
  

闽ICP备14008679号