總結為兩種方法,一種是後端使用freemarker,一種是前端使用js插件。兩種方法各有利弊。前端的比較簡單,但是格式容易出現問題。後端的比較穩定,但是較前端來說更為繁瑣。一般更加傾向于後端的寫法。
一、後端使用freemarker
1、導入maven依賴
org.freemarker
freemarker
2.3.28
2、制作模闆檔案
首先建立一個doc文檔,如下圖:
這個文檔就是你大緻需要生成的樣子。圖檔可以随意,這裡這是利用這張圖檔在這裡占個位置。
将該文檔儲存為2003 xml:
然後用XML文本編輯器打開該檔案,這裡推薦一個工具Firstobject free XML editor,下載下傳位址:Firstobject free XML editor
用工具打開這個檔案,可以看到裡面的代碼很多很亂,不要慌,用ctrl+F找到你需要動态生成的标題或者文字:
将其改為${title}:
接下來改圖檔占位符,找到結尾為preserve的标簽:
将後面的一大堆圖檔的代碼删除,然後改為你圖檔的占位符:${img}:
将該檔案另存為ftl檔案:
3、使用getDataURl()方法擷取echarts圖檔base64碼,并傳給背景
var stinkEcharts1 = function (data) {
option = {
legend: {},
tooltip: {},
dataset: {
dimensions: ['time', 'CH4', 'NH3', 'H2S','VOCs'],
source: data
},
xAxis: {type: 'category'},
yAxis: {},
// Declare several bar series, each will be mapped
// to a column of dataset.source by default.
series: [
{animation: false,type: 'bar'},
{animation: false,type: 'bar'},
{animation: false,type: 'bar'},
{animation: false,type: 'bar'},
]
};
var chart = echarts.init(document.getElementById('stink1'),'macarons');
chart.setOption(option);
imgStink1 = chart.getDataURL();
}
$.ajax({
type: 'post',
url: "/appcenter/envAssessReport/export1",
data : {
title:$("#ty").text(),
imgStink1:imgStink1,
},
dataType : "json",
success : function (data) {
var map = data.data;
if (map.num==1){
window.location.href='/statics/download/word.docx'
}else {
}
},
})
4、WordUtil工具類
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class WordUtils {
private static final String FTL_FP = "D:/file/"; //模闆路徑
private static Configuration configuration = null;
static{
configuration = new Configuration(Configuration.VERSION_2_3_28);
configuration.setDefaultEncoding("utf-8");//設定預設的編碼
}
public Boolean writeWordReport(String wordFilePath,String wordFileName,String templateFileName, MapbeanParams) {
Writer out = null;
try {
configuration.setDirectoryForTemplateLoading(new File(FTL_FP));
Template template = configuration.getTemplate(templateFileName, "UTF-8");
//擷取檔案目錄,如果不存在則建立
String filePath = "";
int index = wordFilePath.lastIndexOf(File.separator);
if(index != wordFilePath.length()-1){
filePath = wordFilePath+ File.separator;
}else {
filePath = wordFilePath;
}
File file1 = new File(filePath);
if(!file1.exists()){
file1.mkdirs();
}
//輸出檔案
File file = new File(filePath+wordFileName);
FileOutputStream fos = new FileOutputStream(file);
out = new OutputStreamWriter(fos, "UTF-8");
template.process(beanParams, out);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}finally{
try {
if(out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String turn(String str){
String base64 = str.replaceAll(" ", "+");
String[] arr = base64.split("base64,");
String image = arr[1];
return image;
}
}
5、調用WordUtil.java工具類,生成word文檔
public Mapexport(String title,String imgStink1) {
Mapmap = new HashMap<>();
String base64 = imgStink1.replaceAll(" ", "+");
// 資料格式為data:image/png;base64,iVBORw0KGgoAA... 在"base64,"之後的才是圖檔資訊
String[] arr = base64.split("base64,");
String image = arr[1];
//添加模闆資料
MapdataMap = new HashMap<>();
dataMap.put("title",title);
dataMap.put("imgStink1",WordUtils.turn(imgStink1));
//檔案生成路徑
String wordFilePath = "D:/download/";
//檔案生成名稱
String wordFileName = "word.doc";
//模闆檔案名稱
String templateFileName = "word (18).ftl";
//生成word文檔
Boolean result =new WordUtils().writeWordReport(wordFilePath, wordFileName, templateFileName, dataMap);
if(result){
map.put("num",1);
}else {
map.put("num",0);
}
return map;
}
以上就是全部代碼,敲完就可以下載下傳成word文檔了!
注意:如果生成的圖檔看上去或圓或扁,可以在下載下傳的doc文檔中調整好圖檔格式,然後重複步驟2,重新生成模闆檔案,這樣生成的圖檔就是你調整後的樣子。
二、前端js
1、html頁面引入js檔案
js檔案網盤位址:
連結:https://pan.baidu.com/s/1TtrJObbLPq6Mq3hQBd7UcQ
提取碼:f7c4
2、html頁面
環境評估報表年表
1、園區臭氣監測
表 1.1 臭氣資料超标情況彙總柱狀圖
3、js頁面代碼
$("#export").click(function (event) {
var clone = $("#main").clone();//現将頁面clone,以免格式收到影響
var charts = clone.find(".chart");
var flag = charts.length;
var count=0;
for(var i = 0; i < charts.length; i++) {
var curEchart = echarts.getInstanceByDom(charts[i]);
if(curEchart) {
var base = curEchart.getDataURL();
flag--;
}
if(base!=undefined){
var img = $('
');
$(charts[i]).html(img);
}
}
//
var interval = setInterval(function() {
if(true) {
clearInterval(interval);
//導出word
clone.wordExport("word文檔");
}
}, 200)
})