jxl在ssh中导出excel

网上有各种的版本,但是还是自己来总结一下

1.首先是引入jxl的jar包jxl-2.6.10.jar

2.在jsp页面先,这个是跟查询一起的,也就是能够按照搜索条件的不同导出的数据也不同

 

<input type="button" id="searchBut" class="g_btn" value="导出" onclick="$('#export').val('1');validate();"/>
<input type="button" id="searchBut" class="g_btn" value="查询" onclick="$('#export').val('');validate();"/>
<input type="hidden" name="export" id="export" value=""/>也就是export的值为1

 

根据struts2的上传下载操作,需要在struts.xml中配置

 

<result name="excel" type="stream">
	            <param name="contentType">application/vnd.ms-excel</param>
	            <param name="inputName">excelStream</param>
	            <param name="contentDisposition">attachment;filename=${filename}</param>
	            <param name="bufferSize">1024</param>
            </result>

 Action中的处理

private String export;
private InputStream excelStream;
private String filename;
//get set
	public String getExport() {
		return export;
	}
	public void setExport(String export) {
		this.export = export;
	}
	public InputStream getExcelStream() {
		 //将OutputStream转化为InputStream   
        ByteArrayOutputStream out = new ByteArrayOutputStream();   
        export(out);   
        return new ByteArrayInputStream(out.toByteArray()); 
		
	}
	
	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}
	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
public String queryCharge() {
		if("1".equals(export)){
			excelStream=getExcelStream();
	        return "excel";
		}else{
                 return xxx;
}
/**
	 * 导出excel文件
	 * @throws Exception
	 */
	public void export(OutputStream out){ 

        try {
        	//创建工作薄
            WritableWorkbook wwb = Workbook.createWorkbook(out);  
            //创建sheet
            WritableSheet ws = wwb.createSheet("45充值记录", 0);  
            WritableSheet ws2 = wwb.createSheet("60充值记录", 1);  
            WritableSheet ws3 = wwb.createSheet("108充值记录", 2);
            WritableSheet ws4 = wwb.createSheet("其他充值记录", 3);
            //给sheet电子版中所有的列设置默认的列的宽度;  
            ws.getSettings().setDefaultColumnWidth(20); 
            ws2.getSettings().setDefaultColumnWidth(20);  
            ws3.getSettings().setDefaultColumnWidth(20);  
            ws4.getSettings().setDefaultColumnWidth(20);  
           //45的
            String [] str = {"编号","充值类型","充值日期","45充值笔数","任意金额充值总笔数","45充值占当日总充值数百分比"};//标题内容
            ws.addCell(new jxl.write.Label(0,0, "45充值记录表"));
           //60de
            String [] str2 = {"编号","充值类型","充值日期","60充值笔数","任意金额充值总笔数","60充值占当日总充值数百分比"};//标题内容
            ws2.addCell(new jxl.write.Label(0,0,"60充值记录表"));
            //108de
            String [] str3 = {"编号","充值类型","充值日期","108充值笔数","任意金额充值总笔数","108充值占当日总充值数百分比"};//标题内容
            ws3.addCell(new jxl.write.Label(0,0, "108充值记录表"));
           //其他的
            String [] str4 = {"编号","充值类型","充值日期","其他充值笔数","任意金额充值总笔数","其他充值占当日总充值数百分比"};//标题内容
            ws4.addCell(new jxl.write.Label(0,0, "其他充值记录表"));
            List<Map<String, String>> chargeExcelList = manageFundService.queryChargeExcel(reqPara);
            LinkedList<Map<String, String>> list45=new LinkedList<Map<String, String>>();
            LinkedList<Map<String, String>> list60=new LinkedList<Map<String, String>>();
            LinkedList<Map<String, String>> list108=new LinkedList<Map<String, String>>();
            LinkedList<Map<String, String>> listOther=new LinkedList<Map<String, String>>();
            for (Map<String, String> map : chargeExcelList) {
            	if("45".equals(map.get("kind"))){
            		list45.add(map);
            	}else if("60".equals(map.get("kind"))){
            		list60.add(map);
            	}else if("108".equals(map.get("kind"))){
            		list108.add(map);
            	}else if("其他".equals(map.get("kind"))){
            		listOther.add(map);
            	}
			}
            addCellList(list45,ws,str);
            addCellList(list60,ws2,str2);
            addCellList(list108,ws3,str3);
            addCellList(listOther,ws4,str4);
            filename=new String("充值记录.xls".getBytes(),"ISO8859-1");
            wwb.write();  
            wwb.close();
            out.flush();
            out.close();
            
        } catch (Exception e) {  
            System.out.println("Error!");  
            e.printStackTrace();  
        }
	  }  
	 
	/**
	 * 循环添加sheet中的行列
	 * @param list
	 * @param ws
	 */
	public void addCellList(List<Map<String, String>> list, WritableSheet ws,String[] title){
        //添加标题
		try {
			for (int m = 0; m < title.length; m++) {
	            /**
	             * Label(i,j,String);lable是标题,cell是单元格
	             * i:列
	             * j:行
	             * String:表示内容
	             */
	           
				ws.addCell(new Label(m, 1, title[m]));
	        }
			int i=1;
			for (int j = 0; j < list.size(); j++) {  
	        	Map<String, String> map= list.get(j);
	        	if(map!=null && map.size()>0){
	        		// 这里设置是自增的序号而不是ID号.也可以改成ID号ws.addCell(new jxl.write.Label(1, i + 1, ""+  map.get("id"))); 
	    				ws.addCell(new jxl.write.Number(0, i + 1, i));  
	    				ws.addCell(new Label(1, i + 1,map.get("kind")));  
	    				ws.addCell(new Label(2, i + 1,map.get("chargeDay")));  
	    				ws.addCell(new Label(3, i + 1,map.get("thiscnt")));  
	    				ws.addCell(new Label(4, i + 1,map.get("totalCnt")));  
	    				ws.addCell(new Label(5, i + 1,map.get("percentage"))); 
	    				i++;
	        	}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 dao中主要处理的是数据处理的数据,主要是使用native sql写的联合查询,主要查出不同的充值数据

public List<Map<String, String>> queryChargeExcel(FundModel reqPara) {
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		Session session = null;

		try {

			session = sessionFactory.openSession();

			StringBuilder sb = new StringBuilder();
			sb.append("SELECT temp.* FROM(");
			sb.append("SELECT 45 AS kind,a.cnt thiscnt,b.cnt totalCnt, ROUND(a.cnt/b.cnt*100,2) AS percentage,a.chargeDay  FROM( ");
			sb.append("(SELECT COUNT(1) cnt, DATE_FORMAT(charge_time, '%Y-%m-%d') chargeDay ");
			sb.append("FROM t_user_charge ");
			sb.append("WHERE pay_status=1 AND money = 45 ");
			sb.append("GROUP BY chargeDay ");
			sb.append(") a,");
			sb.append("(SELECT COUNT(1) cnt, DATE_FORMAT(charge_time, '%Y-%m-%d') chargeDay ");
			sb.append("FROM t_user_charge ");
			sb.append("WHERE pay_status=1 ");
			sb.append("GROUP BY chargeDay ");
			sb.append(") b");
			sb.append(")");
			sb.append("WHERE a.chargeDay = b.chargeDay ");
			sb.append("UNION ALL ");
			sb.append("SELECT 60,a.cnt thiscnt,b.cnt totalCnt,ROUND(a.cnt/b.cnt*100,2) AS percentage,a.chargeDay FROM( ");
			sb.append("(SELECT COUNT(1) cnt, DATE_FORMAT(charge_time, '%Y-%m-%d') chargeDay ");
			sb.append("FROM t_user_charge  ");
			sb.append("WHERE pay_status=1 AND money = 60  ");
			sb.append("GROUP BY chargeDay ");
			sb.append(") a,");
			sb.append("(SELECT COUNT(1) cnt, DATE_FORMAT(charge_time, '%Y-%m-%d') chargeDay ");
			sb.append("FROM t_user_charge ");
			sb.append("WHERE pay_status=1  ");
			sb.append("GROUP BY chargeDay ");
			sb.append(") b");
			sb.append(")");
			sb.append("WHERE a.chargeDay = b.chargeDay ");
			sb.append("UNION ALL ");
			sb.append("SELECT 108,a.cnt thiscnt,b.cnt totalCnt, ROUND(a.cnt/b.cnt*100,2) AS percentage,a.chargeDay FROM( ");
			sb.append("(SELECT COUNT(1) cnt, DATE_FORMAT(charge_time, '%Y-%m-%d') chargeDay ");
			sb.append("FROM t_user_charge ");
			sb.append("WHERE pay_status=1 AND money = 108  ");
			sb.append("GROUP BY chargeDay ");
			sb.append(") a,");
			sb.append("(SELECT COUNT(1) cnt, DATE_FORMAT(charge_time, '%Y-%m-%d') chargeDay ");
			sb.append("FROM t_user_charge ");
			sb.append("WHERE pay_status=1 ");
			sb.append("GROUP BY chargeDay ");
			sb.append(") b");
			sb.append(")");
			sb.append("WHERE a.chargeDay = b.chargeDay ");
			sb.append(" UNION ALL");
			sb.append(" SELECT '其他',a.cnt thiscnt,b.cnt totalCnt, ROUND(a.cnt/b.cnt*100,2) AS percentage,a.chargeDay FROM(");
			sb.append(" (SELECT COUNT(1) cnt, DATE_FORMAT(charge_time, '%Y-%m-%d') chargeDay");
			sb.append(" FROM t_user_charge");
			sb.append(" WHERE pay_status=1 AND money NOT IN(45,60,108)");
			sb.append(" GROUP BY chargeDay");
			sb.append(" ) a,");
			sb.append(" (SELECT COUNT(1) cnt, DATE_FORMAT(charge_time, '%Y-%m-%d') chargeDay");
			sb.append(" FROM t_user_charge");
			sb.append(" WHERE pay_status=1");
			sb.append(" GROUP BY chargeDay");
			sb.append(" ) b");
			sb.append(" )");
			sb.append(" WHERE a.chargeDay = b.chargeDay");
			sb.append(" ) AS temp");
			sb.append(" WHERE 1=1");
			if (StringUtil.isNotEmpty(reqPara.getBeginTime())) {
				sb.append(" and chargeDay>=:beginTime");
			}
			if (StringUtil.isNotEmpty(reqPara.getEndTime())) {
				sb.append(" and chargeDay<:endTime");
			}
			Query query = session.createSQLQuery(sb.toString());
			if (StringUtil.isNotEmpty(reqPara.getBeginTime())) {
				query.setString("beginTime", reqPara.getBeginTime());
			}
			if (StringUtil.isNotEmpty(reqPara.getEndTime())) {
				query.setString("endTime", TimeUtil.getNextNDaysStr(
						reqPara.getEndTime(), "yyyy-MM-dd", 1));
			}
			List<Object[]> charges = query.list();

			for (Object[] charge : charges) {

				Map<String, String> m = new HashMap<String, String>();

				m.put("kind", charge[0].toString());
				m.put("thiscnt", charge[1].toString());
				m.put("totalCnt", charge[2].toString());
				m.put("percentage", charge[3].toString());
				m.put("chargeDay", charge[4].toString());

				//m.put("generTime", TimeUtil.formatDate((Date) charge[8]));

				data.add(m);
			}

			logger.info("chargesmore:" + data);

		} catch (Exception e) {
			logger.error("querying chargesmore failed", e);
			e.printStackTrace();
		} finally {

			if (session != null && session.isOpen()) {
				session.close();
			}

		}

		return data;
	}

 若是需要加上百分比的话则是

CONCAT(ROUND(a.cnt/b.cnt*100,2),'%')显示的就是50%,嘿嘿

 

这算是一个完整的了,特此记录一下

你可能感兴趣的:(导出Excel)