生活随笔
收集整理的這篇文章主要介紹了
java后端使用freemarker生成echarts图表word
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
項(xiàng)目結(jié)構(gòu)
package com
.example
.demo
.月報(bào)
;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
;@GetMapping(value
= "getFile")public void getFile(HttpServletResponse response
) throws Exception
{echartsService
.getFile(null
, response
);}}
package com
.example
.demo
.月報(bào)
;import javax
.servlet
.http
.HttpServletResponse
;public interface EchartsService {void getFile( StatisticsTableDto statisticsTableDto
, HttpServletResponse response
) throws Exception
;
}
package com
.example
.demo
.月報(bào)
;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
{
ServletOutputStream out
= response
.getOutputStream();String options
= "{\"title\":{\"text\":\"銷售圖\",\"subtext\":\"銷售統(tǒng)計(jì)\",\"x\":\"CENTER\"},\"toolbox\": {\"feature\": {\"saveAsImage\": {\"show\": true,}}},\"tooltip\": {\"show\": true},\"legend\": {\"data\":[\"直接訪問\",\"郵件營銷\",\"聯(lián)盟廣告\",\"視頻廣告\",\"搜索引擎\"]}, \"series\":[{\"name\":\"訪問來源\",\"type\":\"pie\",\"radius\": '55%',\"center\": ['50%', '60%'],\"data\":[{\"value\":335, \"name\":\"直接訪問\"},{\"value\":310, \"name\":\"郵件營銷\"},{\"value\":234, \"name\":\"聯(lián)盟廣告\"},{\"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<>();
map
.put("time", "測試");map
.put("image1", images1
);map
.put("image2", images1
);map
.put("image3", images1
);emw
.createWord(map
, "統(tǒng)計(jì)表.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;while ((len
= input
.read(bytes
, 0, 1024)) != -1) {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 "暫不支持本機(jī)的運(yùn)行系統(tǒng)";}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
;}private static String
writeFile(String options
) {String dataPath
= File
.separator
+ UUID
.randomUUID().toString().substring(0, 8) + ".json";try {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
.月報(bào)
;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");}public void createWord(Map
<String, Object> dataMap
, String templateName
, String saveFilePath
) {config
.setClassForTemplateLoading(this.getClass(), "/templates/");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("解析模板出錯(cuò),請(qǐng)檢查模板格式", 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("輸出文件時(shí)未找到文件", e
);e
.printStackTrace();}out
= new BufferedWriter(new OutputStreamWriter(fos
));try {template
.process(dataMap
, out
);} catch (TemplateException e
) {log
.error("填充模板時(shí)異常", e
);e
.printStackTrace();} catch (IOException e
) {log
.error("IO讀取時(shí)異常", e
);e
.printStackTrace();}log
.info("由模板文件:" + templateName
+ ".ftl" + " 生成文件 :" + saveFilePath
+ " 成功!!");try {if (fos
!= null
) {fos
.close();}out
.close();} catch (Exception e
) {log
.error("關(guān)閉Write對(duì)象出錯(cuò)", e
);e
.printStackTrace();}}}
總結(jié)
以上是生活随笔為你收集整理的java后端使用freemarker生成echarts图表word的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。