前台的jsp页面
<script src="<%=basePath %>scripts/echars/dist/echarts.js"></script>
<script type="text/javascript">
require.config({
paths: {
echarts: '<%=basePath %>scripts/echars/dist'
}
});
require(
[
'echarts',
'echarts/theme/macarons',
'echarts/chart/line',
'echarts/chart/bar'
],
DrawEChart
);
var myChart;
function DrawEChart(ec,theme) {
var chartContainer = document.getElementById("main");
myChart = ec.init(chartContainer,theme);
var categories = [];
var values = [];
// 同步执行
$.ajaxSettings.async = false;
$.getJSON('<%=basePath %>/admin/report/goodOrderData.do' ,function (json){
if(json != null || json != ""){
categories=json.categories;
values=json.values;
}
});
var option = {
title : {
text: '销量统计',
subtext: '销量'
},
tooltip : {
backgroundColor: 'rgba(50,50,50,0.5)',
trigger: 'axis',
axisPointer : { // 坐标轴指示器,坐标轴触发有效
type : 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
legend: {
textStyle: {color: 'red'},
data:['销量']
},
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,
yAxis : [{
name : '销量数量',
type : 'value'
}],
xAxis : [{
name : '商品',
type : 'category',
data : categories
}],
series : [{
name:'销量',
type:'bar',
stack: '总量',
itemStyle: {
normal: {
areaStyle: {
// 区域图,纵向渐变填充
color : (function (){
var zrColor = require('zrender/tool/color');
return zrColor.getLinearGradient(
0, 200, 0, 400,
[[0, 'rgba(72,209,204,0.8)'],[0.8, 'rgba(225,255,255,0.1)']]
)
})()
},
label : {
show : true,
textStyle : {
fontSize : '20',
fontFamily : '宋体',
fontWeight : 'bold'
}
}
}
},
data:values,
markLine : {
data : [
{type : 'average', name : '平均值'},
{type : 'max'},
{type : 'min'}
]
}
}]
};
myChart.setOption(option);
myChart.hideLoading();
}
function openImage(){
var data = myChart.getDataURL("png");
$("#img").val(data);
$("#exportForm").submit();
}
</script>
</head>
<body>
<form action="<%=basePath %>/admin/report/goodOrder.do?deliveryTimes=export" method="post" id="exportForm">
<div id="main" style="height: 400px; border: 1px solid #ccc; padding: 10px;"></div>
<input type="button" class="search-btn" value="导出" onclick="openImage()"/>
<input type="hidden" name="img" id="img" />
</form>
</div>
</body>
</html>
后台---------------------------------------------------------------------------------------------------
基于SpringMVC框架
@RequestMapping("/goodOrder")
public String goodOrder(SaleOrder saleOrder) throws Exception{
String data = request.getParameter("img");
//这里是导出的代码
if("export".equals(saleOrder.getDeliveryTimes())&&(null!= data||""!=data)){
try {
String userName = System.getProperty("user.name");
String filePath = "C:\\Users\\"+userName+"\\Desktop\\chart";
File file = new File(filePath);
if(!file.exists()){
file.mkdir();
}
String fileName = filePath +"\\"+ System.currentTimeMillis()+".png";
createImage( fileName, data);
createExcel(fileName);
return null;
} catch (Exception e) {
e.printStackTrace();
}
}
//这里是生成柱状图的jsp页面
return “页面”;
}
//这里是ajax同步请求获取数据的页面
@RequestMapping("/goodOrderData")
@ResponseBody
public Map<String, Object> goodOrderData(SaleOrder saleOrder) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
//纵坐标值
Integer [] values = new Integer[]{12,33,4,56,5};
//横坐标值
String [] aa= new String[]{"2015-01","2015-02","2015-03","2015-04","2015-05"};
map.put("categories", aa);
map.put("values", values);
return map;
}
public void createImage(String fileName, String data) throws ServletException,IOException {
try {
String[] url = data.split(",");
String u = url[1];
// Base64解码
byte[] b = new BASE64Decoder().decodeBuffer(u);
// 生成图片
OutputStream out = new FileOutputStream(new File(fileName));
out.write(b);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 图片写入Excel中
* @param fileName
* @throws ServletException
* @throws IOException
*/
public void createExcel(String fileName) throws ServletException ,IOException {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("echart");
HSSFRow rows = sheet.createRow(0);
HSSFCell cells = rows.createCell(40);
// 另一个样式
// 设置字体
HSSFFont headfont = wb.createFont();
headfont.setFontName("新宋体");
headfont.setFontHeightInPoints((short) 18);// 字体大小
headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
HSSFCellStyle headstyle = wb.createCellStyle();
headstyle.setFont(headfont);
headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
headstyle.setLocked(true);
headstyle.setWrapText(true);// 自动换行
HSSFRow row0 = sheet.createRow(0);
// 设置行高
row0.setHeight((short) 900);
// 创建第一列
HSSFCell cell0 = row0.createCell(0);
String header = "关于统计报表";
cell0.setCellValue(new HSSFRichTextString(header));
cell0.setCellStyle(headstyle);
//合并
CellRangeAddress range = new CellRangeAddress(0, 0, 0, 14);
sheet.addMergedRegion(range);
//
cells.setCellType(HSSFCell.CELL_TYPE_BLANK);
ByteArrayOutputStream outStream = new ByteArrayOutputStream(); // 将图片写入流中
BufferedImage bufferImg = ImageIO.read(new File(fileName));
ImageIO.write(bufferImg, "PNG", outStream); // 利用HSSFPatriarch将图片写入EXCEL
HSSFPatriarch patri = sheet.createDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor(20, 20, 20,20,
(short) 0, 1, (short) 15, 20);
patri.createPicture(anchor, wb.addPicture(
outStream.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
long name = System.currentTimeMillis();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String currentDate = df.format(new Date());
String pngName =currentDate+name+".xls";
try {
OutputStream out = null;
response.reset();
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(pngName, "UTF-8"));
out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}