');require.config({paths:{'echarts':'js/echarts','e" />

echarts图表与列表文字结合导出word文档

echarts图表与列表文字结合导出word文档
echarts图表与列表文字结合导出word文档

导出word文件需要jar包

Echarts图表可以生成BASE64编码

function inita(hotWords,word,xData,hotWordtwo)

{

// alert(xData);

//$("#chart_wrapper").append('

class="pro_zline" id="pro_zline'+i+'">

');

require.config({

paths: {

'echarts' : 'js/echarts',

'echarts/chart/line' : 'js/echarts', //饼状图

'echarts/chart/bar' : 'js/echarts'//柱状图

}

});

require(

[

'echarts',

'echarts/chart/line', // 按需加载所需图表,如需动态类型切换功能,别忘了同时加载相应图表

'echarts/chart/bar'

],

function (ec) {

// 基于准备好的dom,初始化echarts图表

var myChart = ec.init(document.getElementById(word));

var option = {

grid :{

},

tooltip : {

trigger: 'axis'

},

toolbox: {

show :true,

feature : {

mark : {show: true},

dataView : {show: true, readOnly: false},

magicType : {show: true, type: ['line', 'bar']},

restore : {show: true},

saveAsImage : {show: true}

}

},

calculable :true,

animation :false,

legend: {

data:['来电量','昨日数据对比']

},

xAxis : [

{

type :'category',

data :xData

}

],

yAxis : [

{

type :'value',

name : '来电量',

axisLabel : {

formatter: '{value}'

}

},

{

type :'value',

name : '昨日数据对比',

axisLabel : {

formatter: '{value}%'

}

}

],

series :[

{

name:'来电量',

type:"bar",

data:getPlatData(hotWords)

},

{

name:'昨日数据对比',

type:"line",

yAxisIndex: 1,

data:getPlatData(hotWordtwo)

}

]

};

// 为echarts对象加载数据

myChart.setOption(option);

$("#image1").val(myChart.getDataURL('png'));

// alert( myChart.getDataURL('png'))//获取base64编码

}

);

}

获取base64编码图片后要传到后台

function AllAreaWord()

{var date =$("#year").val();

$.ajax({

type:'POST',

url:'briefing/exp', //用户请求数据的URL

data:"&date="+date+"&image1="+$("#image1").val()+"&image2="+$("#image 2").val(),

beforeSend:function () { changeImg(); },

error:function (XMLHttpRequest, textStatus, errorThrown) {

alert(textStatus);

},

success: function (data) {

window.location.href

="<%=basePath%>briefing/expword?date="+encodeURI(date); //后台将

base64编码图片保存session中在执行导出word

}

});

}

后台处理将图片编码存到session中

@RequestMapping(value="exp")//简报生成echarts图表

public String exp(Model model,HttpServletRequest request){ String image1 = request.getParameter("image1");

String image2 = request.getParameter("image2");

String[] url = image1.split(",");

String[] url2 = image2.split(",");

String imageo="";

String imaget="";

if(image1!=""&&url.length>1){

imageo=url[1];

}

if(image2!=null&&url2.length>1){

imaget=url2[1];

}

request.getSession().setAttribute(SystemConstant.SESSION_IMGONE, imageo);

request.getSession().setAttribute(SystemConstant.SESSION_IMGTWO, imaget);

return"waihu/generation";

}

后台导出word

先建一个类

packagecom.ideal.mall.front.web.controller;

importjava.io.ByteArrayInputStream;

importjava.io.IOException;

importjava.io.InputStream;

importjava.util.Iterator;

importjava.util.List;

importjava.util.Map;

importjava.util.Map.Entry;

importorg.apache.poi.POIXMLDocument;

import org.apache.poi.openxml4j.opc.OPCPackage;

https://www.360docs.net/doc/d813049904.html,ermodel.XWPFParagraph;

https://www.360docs.net/doc/d813049904.html,ermodel.XWPFRun;

https://www.360docs.net/doc/d813049904.html,ermodel.XWPFTable;

https://www.360docs.net/doc/d813049904.html,ermodel.XWPFTableCell;

https://www.360docs.net/doc/d813049904.html,ermodel.XWPFTableRow;

/**

* 适用于word 2007

* poi 版本 3.7

*/

public class WordUtil {

/**

* 根据指定的参数值、模板,生成 word 文档

* @paramparam需要替换的变量

* @param template 模板

*/

public static CustomXWPFDocumentgenerateWord(Mapparam, String template) {

CustomXWPFDocument doc = null;

try {

OPCPackage pack = POIXMLDocument.openPackage(template);

doc = new CustomXWPFDocument(pack);

if (param != null &¶m.size() > 0) {

//处理段落

ListparagraphList = doc.getParagraphs(); processParagraphs(paragraphList, param, doc);

//处理表格

Iterator it = doc.getTablesIterator();

while (it.hasNext()) {

XWPFTable table = it.next();

List rows = table.getRows();

for (XWPFTableRow row : rows) {

List cells = row.getTableCells(); for (XWPFTableCell cell : cells) {

ListparagraphListTable=

cell.getParagraphs();

processParagraphs(paragraphListTable, param, doc);

}

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

return doc;

}

/**

* 处理段落

* @paramparagraphList

*/

public static void processParagraphs(ListparagraphList,Mapparam,CustomXWPFDocument doc){

if(paragraphList != null &¶graphList.size() > 0){

for(XWPFParagraphparagraph:paragraphList){

List runs = paragraph.getRuns();

for (XWPFRun run : runs) {

String text = run.getText(0);

if(text != null){

booleanisSetText = false;

for (Entry entry : param.entrySet()) {

String key = entry.getKey();

if(text.indexOf(key) != -1){

isSetText = true;

Object value = entry.getValue();

if (value instanceof String) {//文本替换

text = text.replace(key, value.toString());

} else if (value instanceof Map) {//图片替换text = text.replace(key, "");

Map pic = (Map)value;

int width = Integer.parseInt(pic.get("width").toString());

int height = Integer.parseInt(pic.get("height").toString()); intpicType = getPictureType(pic.get("type").toString());

byte[] byteArray = (byte[]) pic.get("content"); ByteArrayInputStreambyteInputStream = new ByteArrayInputStream(byteArray);

try {

intind = doc.addPicture(byteInputStream,picType);

doc.createPicture(ind, width , height,paragraph);

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

if(isSetText){

run.setText(text,0);

}

}

}

}

}

}

/**

* 根据图片类型,取得对应的图片类型代码

* @parampicType

* @return int

*/

private static intgetPictureType(String picType){

int res = CustomXWPFDocument.PICTURE_TYPE_PICT;

if(picType != null){

if(picType.equalsIgnoreCase("png")){

res = CustomXWPFDocument.PICTURE_TYPE_PNG;

}else if(picType.equalsIgnoreCase("dib")){

res = CustomXWPFDocument.PICTURE_TYPE_DIB;

}else if(picType.equalsIgnoreCase("emf")){

res = CustomXWPFDocument.PICTURE_TYPE_EMF;

}else if(picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")){

res = CustomXWPFDocument.PICTURE_TYPE_JPEG;

}else if(picType.equalsIgnoreCase("wmf")){

res = CustomXWPFDocument.PICTURE_TYPE_WMF;

}

}

return res;

}

/**

* 将输入流中的数据写入字节数组

* @param in

* @return

*/

public static byte[] inputStream2ByteArray(InputStreamin,booleanisClose){

byte[] byteArray = null;

try {

int total = in.available();

byteArray = new byte[total];

in.read(byteArray);

} catch (IOException e) {

e.printStackTrace();

}finally{

if(isClose){

try {

in.close();

} catch (Exception e2) {

System.out.println("关闭流失败");

}

}

}

returnbyteArray;

}

}

后台导出

@RequestMapping(value="exp")//简报生成echarts图表

public String exp(Model model,HttpServletRequest request){ String image1 = request.getParameter("image1");

String image2 = request.getParameter("image2");

String[] url = image1.split(",");

String[] url2 = image2.split(",");

String imageo="";

String imaget="";

if(image1!=""&&url.length>1){

imageo=url[1];

}

if(image2!=null&&url2.length>1){

imaget=url2[1];

}

request.getSession().setAttribute(SystemConstant.SESSION_IMGONE, imageo);

request.getSession().setAttribute(SystemConstant.SESSION_IMGTWO, imaget);

return"waihu/generation";

}

@RequestMapping(value="expword")//简报生成

@ResponseBody

publicvoid expword(MapdataMap,Modelmodel,HttpServletRequestrequest ,HttpServletResponse response) throws Exception{

String userId = request.getParameter("userId");

String date1 = request.getParameter("date");

String imageo = (String)

request.getSession().getAttribute(SystemConstant.SESSION_IMGONE);

String imaget = (String)

request.getSession().getAttribute(SystemConstant.SESSION_IMGTWO);

Calendar cal = Calendar.getInstance();

cal.add(Calendar.DATE, -1);

String yesterday =

new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());

if(date1==null){

date1=yesterday;

}

Listzxlist = workListService.queryByWorkList(date1,"咨询类");

Listqzlist = workListService.queryByWorkList(date1,"求助投诉类");

Listrdlist = workListService.queryByconType(date1,"5");

Briefing briefing1 = new Briefing();

Briefing briefing =briefingService.getBriefing(date1,"");

if(briefing==null){

Listlist = workListService.queryByType(date1,"");

for(int i=0;i

if(i==0){

briefing1.setContentOne(list.get(i).toString());

}if(i==1){

briefing1.setContentTwo(list.get(i).toString());

}

}

briefing1.setContent("");

}else{

briefing1=briefing;

}

String aa= imageo.replaceAll(" ","\\+");

String bb= imaget.replaceAll(" ","\\+");

BASE64Decoder decoder = new BASE64Decoder();

byte[] a = decoder.decodeBuffer(aa);

byte[] b = decoder.decodeBuffer(bb);

testTemplateWrite(zxlist,qzlist,rdlist,briefing1,date1,a,b,respon se);

}

publicvoid testTemplateWrite(Listzxlist,Listqzlist,Listrdlist,Brie fingbriefing,Stringdate,byte[] image1,byte[]

image2,HttpServletResponse response) throws Exception { Mapparams = new HashMap();

String tomcatPath=System.getProperty("user.dir");

Map header = new HashMap();

header.put("width", 550);

header.put("height", 150);

header.put("type", "png");

header.put("content", image1);

params.put("${image1}",header);

Map headers = new HashMap();

headers.put("width", 550);

headers.put("height", 150);

headers.put("type", "png");

headers.put("content", image2);

params.put("${image2}",headers);

params.put("${date}", date);

params.put("${content0}", briefing.getContent());

params.put("${content1}", briefing.getContentOne());

params.put("${content2}", briefing.getContentTwo());

String filepath = "";

if (tomcatPath.contains("\\")) {

filepath = tomcatPath.replace("\\bin",

"\\webapps\\army-infantry\\fileData\\") + "rxjbmb.docx";

}

InputStream is = new FileInputStream(filepath);

CustomXWPFDocument doc = new CustomXWPFDocument(is);

//替换表格里面的变量

if(zxlist.size()!=0){

insertValueToTable(doc, generateTestData(zxlist),1,false);

}

if(qzlist.size()!=0){

insertValueToTable(doc, generateTestData(qzlist),2,true);

}

if(rdlist.size()!=0){

insertValueToTable(doc, generateTestDatas(rdlist),2,true);

}

//替换段落里面的变量

ListparagraphList = doc.getParagraphs();

WordUtil.processParagraphs(paragraphList, params, doc);

String fileName =date+"热线简报.docx";

response.reset();

ServletOutputStream out = response.getOutputStream();

response.setContentType("application/vnd.ms-excel");

response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));

BufferedInputStreambis = null;

BufferedOutputStreambos = null;

try {

bis =new BufferedInputStream(new FileInputStream(filepath));

bos = new BufferedOutputStream(out);

doc.write(out);

} catch (IOException e) { throw e;

} finally {

if (bis != null)

bis.close();

if (bos != null)

bos.close();

}

this.close(is);

public List>generateTestData(List lists) { List>resultList = new ArrayList>();

for (int i = 0; i

List list = new ArrayList();

Object[] obj =(Object[]) lists.get(i);

String obj6="0%";

if(obj[6]!=null){

obj6= obj[6].toString()+"%";

}

String obj7="0%";

if(obj[7]!=null){

obj7= obj[7].toString()+"%";

}

list.add(obj[0].toString());

list.add(obj[1].toString());

list.add(obj[2].toString());

list.add(obj[3].toString());

list.add(obj[4].toString());

list.add(obj[5].toString());

list.add(obj6);

list.add(obj7);

resultList.add(list);

}

return resultList;

}

public List>generateTestDatas(List lists) { List>resultList = new ArrayList>();

for (int i = 0; i

List list = new ArrayList();

Object[] obj =(Object[]) lists.get(i);

String obj3="0%";

if(obj[3]!=null){

obj3= obj[3].toString()+"%";

}

list.add(obj[0].toString());

list.add(obj[1].toString());

list.add(obj[2].toString());

list.add(obj3);

resultList.add(list);

}

return resultList;

publicvoid insertValueToTable(XWPFDocument doc,

List>resultList,int tableRowSize,boolean isDelTmpRow) throws Exception {

Iterator iterator = doc.getTablesIterator();

XWPFTable table = null;

List rows=null;

List cells=null;

ListtmpCells=null;//模版列

XWPFTableRowtmpRow=null;//匹配用

XWPFTableCelltmpCell=null;//匹配用

boolean flag=false;//是否找到表格

while (iterator.hasNext()) {

table = iterator.next();

rows = table.getRows();

if(rows.size()==tableRowSize){

tmpRow=rows.get(tableRowSize-1);

cells =tmpRow.getTableCells();

if(cells.size()==resultList.get(0).size()){

flag=true;

break;

}

}

}

if(!flag){

return;

}

tmpCells=tmpRow.getTableCells();

for(int i=0,len=resultList.size();i

XWPFTableRow row=table.createRow();

row.setHeight(tmpRow.getHeight());

List list=resultList.get(i);

cells=row.getTableCells();

//插入的行会填充与表格第一行相同的列数

for(int k=0,klen=cells.size();k

tmpCell=tmpCells.get(k);

XWPFTableCell cell=cells.get(k);

setCellText(tmpCell, cell, list.get(k));

}

//继续写剩余的列

for(int j=cells.size(),jlen=list.size();j

tmpCell=tmpCells.get(j);

XWPFTableCell cell=row.addNewTableCell();

setCellText(tmpCell, cell, list.get(j));

}

}

//删除模版行

if(isDelTmpRow){

table.removeRow(tableRowSize-1);

}

}

publicvoid setCellText(XWPFTableCelltmpCell,XWPFTableCellcell,Stri ng text) throws Exception{

CTTc cttc2 = tmpCell.getCTTc();

CTTcPr ctPr2=cttc2.getTcPr();

CTTccttc = cell.getCTTc();

CTTcPrctPr = cttc.addNewTcPr();

// cell.setColor(tmpCell.getColor());

// cell.setVerticalAlignment(tmpCell.getVerticalAlignment());

if(ctPr2.getTcW()!=null){

ctPr.addNewTcW().setW(ctPr2.getTcW().getW());

}

// if(ctPr2.getVAlign()!=null){最新注释

// ctPr.addNewVAlign().setVal(ctPr2.getVAlign().getVal());

// }

if(cttc2.getPList().size()>0){

CTP ctp=cttc2.getPList().get(0);

if(ctp.getPPr()!=null){

if(ctp.getPPr().getJc()!=null){

cttc.getPList().get(0).addNewPPr().addNewJc().setVal(ctp.getPPr() .getJc().getVal());

}

}

}

// if(ctPr2.getTcBorders()!=null){

// ctPr.setTcBorders(ctPr2.getTcBorders());

// }

XWPFParagraphtmpP=tmpCell.getParagraphs().get(0);

XWPFParagraphcellP=cell.getParagraphs().get(0);

XWPFRuntmpR =null;

if(tmpP.getRuns()!=null&&tmpP.getRuns().size()>0){

tmpR=tmpP.getRuns().get(0);

}

XWPFRuncellR = cellP.createRun();

cellR.setText(text);

//复制字体信息

if(tmpR!=null){

cellR.setBold(tmpR.isBold());

cellR.setItalic(tmpR.isItalic());

cellR.setStrike(tmpR.isStrike());

cellR.setUnderline(tmpR.getUnderline());

// cellR.setColor(tmpR.getColor());

cellR.setTextPosition(tmpR.getTextPosition());

if(tmpR.getFontSize()!=-1){

cellR.setFontSize(tmpR.getFontSize());

}

if(tmpR.getFontFamily()!=null){

cellR.setFontFamily(tmpR.getFontFamily());

}

if(tmpR.getCTR()!=null){

if(tmpR.getCTR().isSetRPr()){

CTRPrtmpRPr =tmpR.getCTR().getRPr();

if(tmpRPr.isSetRFonts()){

CTFontstmpFonts=tmpRPr.getRFonts();

CTRPrcellRPr=cellR.getCTR().isSetRPr() ?

cellR.getCTR().getRPr() : cellR.getCTR().addNewRPr();

CTFontscellFonts = cellRPr.isSetRFonts() ? cellRPr.getRFonts() : cellRPr.addNewRFonts();

cellFonts.setAscii(tmpFonts.getAscii());

cellFonts.setAsciiTheme(tmpFonts.getAsciiTheme());

cellFonts.setCs(tmpFonts.getCs());

cellFonts.setCstheme(tmpFonts.getCstheme());

cellFonts.setEastAsia(tmpFonts.getEastAsia());

cellFonts.setEastAsiaTheme(tmpFonts.getEastAsiaTheme());

cellFonts.setHAnsi(tmpFonts.getHAnsi());

cellFonts.setHAnsiTheme(tmpFonts.getHAnsiTheme());

}

}

}

}

//复制段落信息

cellP.setAlignment(tmpP.getAlignment());

cellP.setVerticalAlignment(tmpP.getVerticalAlignment());

cellP.setBorderBetween(tmpP.getBorderBetween());

cellP.setBorderBottom(tmpP.getBorderBottom());

cellP.setBorderLeft(tmpP.getBorderLeft());

cellP.setBorderRight(tmpP.getBorderRight());

cellP.setBorderTop(tmpP.getBorderTop());

cellP.setPageBreak(tmpP.isPageBreak());

if(tmpP.getCTP()!=null){

if(tmpP.getCTP().getPPr()!=null){

CTPPrtmpPPr = tmpP.getCTP().getPPr();

CTPPrcellPPr = cellP.getCTP().getPPr() != null ?

cellP.getCTP().getPPr() : cellP.getCTP().addNewPPr();

//复制段落间距信息

CTSpacingtmpSpacing =tmpPPr.getSpacing();

if(tmpSpacing!=null){

CTSpacingcellSpacing=

cellPPr.getSpacing()!=null?cellPPr.getSpacing():cellPPr.addNewSpacing ();

if(tmpSpacing.getAfter()!=null){

cellSpacing.setAfter(tmpSpacing.getAfter());

}

if(tmpSpacing.getAfterAutospacing()!=null){

cellSpacing.setAfterAutospacing(tmpSpacing.getAfterAutospacing()) ;

}

if(tmpSpacing.getAfterLines()!=null){

cellSpacing.setAfterLines(tmpSpacing.getAfterLines());

}

if(tmpSpacing.getBefore()!=null){

cellSpacing.setBefore(tmpSpacing.getBefore());

}

if(tmpSpacing.getBeforeAutospacing()!=null){

cellSpacing.setBeforeAutospacing(tmpSpacing.getBeforeAutospacing( ));

}

if(tmpSpacing.getBeforeLines()!=null){

cellSpacing.setBeforeLines(tmpSpacing.getBeforeLines());

}

if(tmpSpacing.getLine()!=null){

cellSpacing.setLine(tmpSpacing.getLine());

}

if(tmpSpacing.getLineRule()!=null){

cellSpacing.setLineRule(tmpSpacing.getLineRule());

}

}

//复制段落缩进信息

CTIndtmpInd=tmpPPr.getInd();

if(tmpInd!=null){

CTInd

cellInd=cellPPr.getInd()!=null?cellPPr.getInd():cellPPr.addNewInd();

if(tmpInd.getFirstLine()!=null){

cellInd.setFirstLine(tmpInd.getFirstLine());

}

if(tmpInd.getFirstLineChars()!=null){

cellInd.setFirstLineChars(tmpInd.getFirstLineChars());

}

if(tmpInd.getHanging()!=null){

cellInd.setHanging(tmpInd.getHanging());

}

if(tmpInd.getHangingChars()!=null){

cellInd.setHangingChars(tmpInd.getHangingChars());

}

if(tmpInd.getLeft()!=null){

cellInd.setLeft(tmpInd.getLeft());

}

if(tmpInd.getLeftChars()!=null){

cellInd.setLeftChars(tmpInd.getLeftChars());

}

if(tmpInd.getRight()!=null){

cellInd.setRight(tmpInd.getRight());

}

if(tmpInd.getRightChars()!=null){

cellInd.setRightChars(tmpInd.getRightChars());

}

}

}

}

}

publicvoid saveDocument(XWPFDocumentdocument,StringsavePath) throws Exception{

FileOutputStreamfos = new FileOutputStream(savePath);

document.write(fos);

fos.close();

}

/**

* 正则匹配字符串

* @param str

* @return

*/

private Matcher matcher(String str) {

Pattern pattern = https://www.360docs.net/doc/d813049904.html,pile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);

Matcher matcher = pattern.matcher(str);

return matcher;

}

/**

* 关闭输入流

* @param is

*/

privatevoid close(InputStream is) {

if (is != null) {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

模版

导出的文件

相关主题
相关文档
最新文档