导出 excel表格(数据、echarts图片)

/**
* @Description:导出
* @author: liuc
* @since: 2016年4月14日 上午10:36:39
*/
@RequestMapping("/exportTotalData")
public void exportTotalDataList(HttpServletRequest request,HttpServletResponse response) throws Exception {


String[] sheetNames = { "total" };
String[] excleTitleMsg = {
"custId:客户ID",
"custName:客户名称",
"productName:产品名称",
"cnt:数量", 
"orderPrice:消费金额",
"rechargeDate:充值日期",};
Map paramMap = getParameterMap(request);
String filter = assemblyDataViewSql(
request, Code.TYPE_STATISTIC, "CUSTOM_MANAGER_CUST_ID", "ORG_CODE");
/* String likecustName=request.getParameter("likecustName");
likecustName=java.net.URLDecoder.decode(likecustName, "UTF-8");
paramMap.put("likecustName", likecustName);*/
paramMap.put("filter", filter);
List  list = custDayCheckBillService.find(1, 9999, paramMap).getList();
String filename = "total.xls";
response.reset();
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

ExportExcelProvider.exportExcelByRslt(sheetNames, excleTitleMsg, list, response, null, null);

}



//封装类

package com.liuliangqianbao.common.exportExcel;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletResponse;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**   
*    
* 项目名称:sms-platform   
* 类名称:ExportExcelProvider   
* 类描述: 提供 导出excel的方法  exportExcel()
* 创建人:zhangwei   
* 创建时间:2014-9-26 下午03:48:03   
* 修改人:zhangwei
* 修改时间:2014-9-26 下午03:48:03   
* 修改备注:   
* @version    
*    
*/ 
public class ExportExcelProvider {
    /**
     * 
     * @param sheetNames:sheet的名称 数组
     * @param excleTitleMsg: 数组元素格式 -非模板类型:bean的Field或者Map的key | 类型(String) :title名称    模板类型:bean的Field或者Map的key:none
     * @param datalist:结果集List, 元素为Bean 或者是Map 
     * @param response: HttpServletResponse 
     * @param templetInputIo:Excel固定表头的模板流  
     * @param imageSheets :  类型Map  用来在excel中显示图片,图片以ByteArrayOutputStream输出。
    */

    public static void exportExcelByRslt(String[] sheetNames ,String[] excleTitleMsg,List datalist,HttpServletResponse response,InputStream templetInputIo,Map imageSheets ) throws Exception{
    TableModel data = new DefaultTableModel(datalist.size()+1,excleTitleMsg.length);
    List  colFieldNamelist = new ArrayList();
    //获取 结果集中对象的属性名和标题 添加到TableModel中   
    if(excleTitleMsg.length>0){  // --判断是否是模板文件
    for(int i=0;i     String[] temp = excleTitleMsg[i].split(":");
    colFieldNamelist.add(temp[0]);
    data.setValueAt(temp[1], 0, i);
    }
    }
    //添加结果集中的数据到TableModel中
    for(int rowIndex=0;rowIndex     Object object=datalist.get(rowIndex);
    int temprowindex=rowIndex+1;
    for(int colIndex=0;colIndex     String[] colFieldName=colFieldNamelist.get(colIndex).split("\\|");
    String fieldName = colFieldName[0];
    String fieldType = "";
    if(colFieldName.length>1){
    fieldType = colFieldName[1];
    }
    if(object instanceof HashMap){
    if(fieldType.equals("String")){
    data.setValueAt(String.valueOf(((HashMap) object).get(fieldName)), temprowindex, colIndex);
    }else{
    data.setValueAt(((HashMap) object).get(fieldName), temprowindex, colIndex);
    }
    }else{//List中的元素是Bean
    if(fieldType.equals("String")){
        Object valueObject=getFieldValueByName(fieldName,object);
        data.setValueAt(String.valueOf(valueObject), temprowindex, colIndex);
    }else{
            Object valueObject=getFieldValueByName(fieldName,object);
        data.setValueAt(valueObject, temprowindex, colIndex);
    }
    }
   
    }
    }
    ByteArrayOutputStream bos = null;
    InputStream fis = templetInputIo;
OutputStream fos = null;
try {
fos =response.getOutputStream();
bos = new ByteArrayOutputStream();
TableModel[] tables = {data};
// ExcelWriter.write(fis,bos,sheetNames,tables);
ExcelWriter.write(fis, bos, sheetNames, tables, null, null, false, 2, imageSheets);
bos.writeTo(fos);
bos.flush();
} catch (Exception e1) {
e1.printStackTrace();
}finally{
if(bos != null){
try{bos.close();}catch(Exception e){}
}
//关闭模板流
if(fis != null){
try{fis.close();}catch(Exception e){}
}
//关闭response提供的响应流
if(fos != null){
try{fos.close();}catch(Exception e){}
}
}
     }
         
     /**
      * Description: 根据属性名获取属性值
      * @param fieldName
      * @param 
      * @return 属性值
     */
     protected static Object getFieldValueByName(String fieldName, Object o) {
       try { 
           String firstLetter = fieldName.substring(0, 1).toUpperCase(); 
           String getter = "get" + firstLetter + fieldName.substring(1); 
           Method method = o.getClass().getMethod(getter, new Class[] {}); 
           Object value = method.invoke(o, new Object[] {}); 
           return value; 
       } catch (Exception e) {
        e.printStackTrace();
           return null; 
       } 
   } 
}


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

//导出echarts图片及列表数据至excel表格

-------------------------------------------------------------------------------------------------------------------JSP页面--------------------------------------------------------------------------------------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="q" uri="/query-tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> 





href="${pageContext.request.contextPath}/css/style.css" type="text/css">
href="${pageContext.request.contextPath}/css/admin.css" type="text/css">









 

































;
;
;
;








    客户信息:

        运营商:

       供应商:

        渠道信息:




         日期 : 

至 




查询


重置


导出







data-options="  title: '归属地充值统计',
method: 'post',
url: '${pageContext.request.contextPath }/belongingTopStatistics/findList',
pagination: 'true',
pagePosition: 'bottom',
pageNumber: 1,
pageSize: '10',
rownumbers: 'true',
fit: 'true',
view:myview,
fitColumns: 'true',
fixed: 'true',
loadMsg: '加载中,请稍后..'">






充值省份 充值数量 销售额(元) 盈利额(元)




加载echarts中...



--------------------------------------------------------------------------------------------------------------后台java代码-------------------------------------------------------------------------------------------------------


/**
* @Description:导出
* @author: yys
* @since: 2016年10月26日 上午10:36:39
*/
@RequestMapping("/exportTotalData")
public void exportTotalDataList(HttpServletRequest request,HttpServletResponse response) throws Exception {


String[] sheetNames = { "belongingReport" };
String[] excleTitleMsg = {
"provName:充值省份",
"cnt:充值数量(笔)",
"sales:销售额(元)",
"profit:盈利额(元)",
};
Map paramsMap = getParameterMap(request);

Object startTime=paramsMap.get("startTime");
Object endTime=paramsMap.get("endTime");
Object userIds=paramsMap.get("userIds");
Object supplierCodes=paramsMap.get("supplierCodes");
Object OperatorSids=paramsMap.get("OperatorSids");
if(userIds!=null){
userIds=userIds.toString().split(",");
paramsMap.put("userIds", userIds);
}if(supplierCodes!=null){
supplierCodes=supplierCodes.toString().split(",");
paramsMap.put("supplierCodes", supplierCodes);
}if(OperatorSids!=null){
OperatorSids=OperatorSids.toString().split(",");
paramsMap.put("OperatorSids", OperatorSids);
}
String nowTime="";
if((startTime==null || startTime=="")&&(endTime==null || endTime=="")){

Date dt=new Date();//如果不需要格式,可直接用dt,dt就是当前系统时间
DateFormat df = new SimpleDateFormat("yyyyMMdd");//设置显示格式
nowTime= df.format(dt);
String st=nowTime.substring(0, nowTime.length()-2);
paramsMap.put("startTime", st+"01");
paramsMap.put("endTime", nowTime);
}else{
paramsMap.put("startTime", startTime);
paramsMap.put("endTime", endTime);
}
String filter = assemblyDataViewSql(
request, Code.TYPE_STATISTIC, "CUSTOM_MANAGER_CUST_ID", "ORG_CODE");
paramsMap.put("filter", filter);
List  list = supplierInfoService.findBelongingList(1, 9999, paramsMap).getList();

if(list!=null&&list.size()>0){
String OperatorSid[] = new String[list.size()];
String provCode[] = new String[list.size()];
for(int i=0;i OperatorSid[i] = list.get(i).getOperatorSid();
provCode[i]=list.get(i).getProvCode();
}
Map param=new HashMap();
param.put("channelCodes", OperatorSid);
param.put("provCodes", provCode);
List platformUserInfo=null;
List province=null;
if(OperatorSid.length>0||provCode.length>0){
//获取客户信息
try {
if(OperatorSid.length>0){
platformUserInfo=virtualOperatorChannelService.findOperatorChannelName(param);
for(VirtualOperatorChannel age:platformUserInfo){
String cust=age.getChannelCode().toString();
for(SupplierMonthlySummary li:list){
if(cust.equals(li.getOperatorSid())){
li.setOperatorName(age.getOperatorChannelName());
}
}

}
}
if(provCode.length>0){
province=provinceService.findProvName(param);
for(Province age:province){
String cust=age.getProvCode().toString();
for(SupplierMonthlySummary li:list){
if(cust.equals(li.getProvCode())){
li.setProvName(age.getCnName());
}
}

}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
double sale=0;double profi=0;double cnt=0;
for(SupplierMonthlySummary lis:list){
if(lis.getSales()==null){
lis.setSales(new BigDecimal(0.00));
}if(lis.getProfit()==null){
lis.setProfit(new BigDecimal(0.00));
}if(lis.getCnt()==null){
lis.setCnt("0.00");
}
double nn=lis.getSales().doubleValue();
double nb=lis.getProfit().doubleValue();
double cn=Double.parseDouble(lis.getCnt());
profi=profi+nb;
sale=sale+nn;
cnt=cnt+cn;
}
SupplierMonthlySummary Summary=new SupplierMonthlySummary();
Summary.setProvName("合计:");
Summary.setSales(new BigDecimal(new java.text.DecimalFormat("#.000").format(sale)));
Summary.setProfit(new BigDecimal(new java.text.DecimalFormat("#.000").format(profi)));
Summary.setCnt(Double.toString(cnt));
list.add(Summary);
//echarce图片
String imgUrl=(String) paramsMap.get("imgUrl");
String fileName=request.getSession().getServletContext().getRealPath("/")+"echarts"+System.currentTimeMillis()+".png";
System.out.println("呵呵"+fileName);
Map imageSheets=new HashMap();
System.out.println("标识:"+imgUrl);
if(imgUrl!=null&&imgUrl!=""){
try {
       String[] url = imgUrl.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();
}
}

ByteArrayOutputStream outStream = new ByteArrayOutputStream(); // 将图片写入流中
BufferedImage bufferImg = ImageIO.read(new File(fileName));
   ImageIO.write(bufferImg, "PNG", outStream); // 利用HSSFPatriarch将图片写入EXCEL
  
   imageSheets.put("echarts", outStream);
   

String filename = "belongingReport.xls";
response.reset();
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
ExportExcelProvider.exportExcelByRslt(sheetNames, excleTitleMsg, list, response, null, imageSheets);
}


你可能感兴趣的:(java)