通过Spring反射机制,实现通用的Excel导出类

阅读更多

Struts2.xml


	
		 
		 
		 
		 
		 
		 
			 
			   pageVo
			 
		 
		 
		 
		 
			
			    application/vnd.ms-excel
			    inputStreamExcel
			    attachment;filename="${fileName}"
			    1024
			
        
	

 

 

导出Excel的工具Jsp

exportexcel.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>


  
    
    导出excel
    


	



 

 

报表页面需要引入  Excel导出工具Jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@include file="/common/in.jsp"%>




贷后查询


    
<%@include file="/common/exportexcel.jsp"%>

 

 

ExportExcelAction.java

package com.microcredit.common.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.microcredit.basicdata.entity.BPSAEXLM;
import com.microcredit.common.service.ExportExcelService;
import com.microcredit.common.util.ExcelUtil;
import com.microcredit.system.SpringUtils;
import com.microcredit.system.exception.MsException;
import com.microcredit.utils.CheckClass;

public class ExportExcelAction extends BaseAction {

	private static final long serialVersionUID = 4383815022290991861L;
	private static final Log log = LogFactory.getLog(ExportExcelAction.class);

	private SpringUtils springUtils;
	private InputStream inputStreamExcel;
	private String fileName;
	
	//注入相应的service
	private ExportExcelService exportExcelService;

	public String getColumnsByPage(){
		try {
			pageVo = this.exportExcelService.getExportExcelByPage(getRequestMap());
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			this.getOpearteFailException(e);
		}
		return SUCCESS;
	}
	
	/**
	 * 导出Excel列表	
	 * @return
	 */
	public String getDownloadExcel(){

		//获取Excel名、页眉、标题
		String excelName = ExcelUtil.charGBK2Utf8(CheckClass.chcString(getRequestMap().get("excelName")));
		String sheetName = ExcelUtil.charGBK2Utf8(CheckClass.chcString(getRequestMap().get("sheetName")));
		String title = ExcelUtil.charGBK2Utf8(CheckClass.chcString(getRequestMap().get("title")));
		
		//获取数据
		List> dataList = new ArrayList>();
		try {
			this.getRequestMap().put("userId", this.getCurrentUser().getUSERID());
			dataList = this.exportExcelService.getDownExportExcelData(getRequestMap());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		//获取列表数据
		try {
			pageVo = this.exportExcelService.getExportExcelByPage(getRequestMap());
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			this.getOpearteFailException(e);
		}
		List BPSAEXLMList = pageVo.getRows();//---没有对应实体

		try {
			ByteArrayOutputStream os = new ByteArrayOutputStream();

			ExcelUtil.createWorkBook(sheetName, title, dataList, BPSAEXLMList).write(os);
			
			byte[] content = os.toByteArray();
			
			String fileNameTemp = excelName + ".xls";
			fileName = ExcelUtil.charGB23122GBK(fileNameTemp);
			inputStreamExcel = new ByteArrayInputStream(content);
			
			os.flush();
			os.close();
			
		} catch (Exception e) {
			throw new MsException("0",new String[]{"导出Eecel异常!"},null,null);
		} finally {
			return "excel";
		}
		
	}

	public ExportExcelService getExportExcelService() {
		return exportExcelService;
	}
	
	public void setExportExcelService(ExportExcelService exportExcelService) {
		this.exportExcelService = exportExcelService;
	}
	
	public InputStream getInputStreamExcel() {
		return inputStreamExcel;
	}

	public void setInputStreamExcel(InputStream inputStreamExcel) {
		this.inputStreamExcel = inputStreamExcel;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	public SpringUtils getSpringUtils() {
		return springUtils;
	}

	public void setSpringUtils(SpringUtils springUtils) {
		this.springUtils = springUtils;
	}
	
	
}

 

ExportExcelService.java

package com.microcredit.common.service;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.microcredit.common.dao.ExportExcelDao;
import com.microcredit.common.util.ExcelUtil;
import com.microcredit.common.vo.PageVo;
import com.microcredit.system.SpringUtils;
import com.microcredit.utils.CheckClass;

@Service("exportExcelService")
@Transactional(readOnly = true)
public class ExportExcelService extends BaseService {
	
	private static final Log log = LogFactory.getLog(ExportExcelService.class);

	@Autowired
	@Qualifier("exportExcelDao")
	private ExportExcelDao exportExcelDao;
	
	@Autowired
	@Qualifier("springUtils")
	private SpringUtils springUtils;
	
	public PageVo getExportExcelByPage(Map map) throws Exception{
		return this.exportExcelDao.getExportExcelByPage(map);
	}
	
	public List> getDownExportExcelData(Map map) throws Exception{
		String serviceName = CheckClass.chcString(map.get("serviceName"));
		String methodName = CheckClass.chcString(map.get("methodName"));
		String queryParams = ExcelUtil.charGBK2Utf8(CheckClass.chcString(map.get("queryParams")));
		String userId = CheckClass.chcString(map.get("userId"));
		
		//通过SpringUtils获取,对应的bean对象
		Object infoService = springUtils.beanFactory.getBean(serviceName);
		//通过bean对象创建的service,和已知的方法名,来获取方法对象
		Method method = ReflectUtils.findDeclaredMethod(infoService.getClass(),methodName, new Class[]{Map.class});
		Map queryMap = (Map)JSONObject.fromObject(queryParams);
		queryMap.put("userId", userId);
		//执行方法,将创建的service对象,以及方法所需参数传进去
		Object obj = method.invoke(infoService, queryMap);
		
		PageVo pageVo = new PageVo();
		if(obj instanceof PageVo){
			pageVo = (PageVo) obj;
		}
		List> dataList = ExcelUtil.transListBean2Map(pageVo.getRows());
		return dataList;
	}
	
	//	public Object getDownExportExcelData(Map map) throws Exception{
	//	String serviceName = CheckClass.chcString(map.get("serviceName"));
	//	String methodName = CheckClass.chcString(map.get("methodName"));
	//	String queryParams = CheckClass.chcString(map.get("queryParams"));
	//	Object infoService = springUtils.beanFactory.getBean(serviceName);
	//	
	//	//查询条件需要带入分页的参数
	//	
	//	Method method = ReflectUtils.findDeclaredMethod(infoService.getClass(),methodName, new Class[]{Map.class});
	//	Map queryMap = (Map)JSONObject.fromObject(queryParams);
	//	Object obj = method.invoke(infoService, queryMap);
	//	List list = new ArrayList();
	//	if(obj instanceof PageVo){
	//		//使用分页查询,需要循环查询分页,每页查询出来的结果拼接到一个List中,
	//		PageVo pageVo = (PageVo) obj;
	//		new BigDecimal(pageVo.getTotal()).divideAndRemainder(new BigDecimal(pageVo.getRows().size()));
	//	} else if(obj instanceof List){
	//		
	//	}
	//}
}

 

 

ExportExcelDaoImpl.java

package com.microcredit.common.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Repository;

import com.microcredit.basicdata.entity.BPSAEXLM;
import com.microcredit.common.dao.ExportExcelDao;
import com.microcredit.common.vo.PageVo;
import com.microcredit.utils.CheckClass;

@Repository("exportExcelDao")
public class ExportExcelDaoImpl extends BaseDaoImpl implements ExportExcelDao	 {

	@Override
	public PageVo getExportExcelByPage(Map map) throws Exception{
		StringBuffer selectSql = new StringBuffer();
		StringBuffer pageSql = new StringBuffer();
		StringBuffer whereSql = new StringBuffer();
		Map params = new HashMap();
		String MODELNAME = CheckClass.chcString(map.get("MODELNAME"));
		String refcodeParams = CheckClass.chcString(map.get("refcodeParams[]"));
		List REFCODE_list = new ArrayList();
		if(!CheckClass.isBlank(refcodeParams)){
			String[] REFCODE = refcodeParams.split(",");
			for (int i = 0; i < REFCODE.length; i++) {
				REFCODE_list.add(REFCODE[i]);
			}
		}

		selectSql.append(" select t.* ");
		pageSql.append( "from BPSAEXLM t "); 
		whereSql.append(" where 1=1 and t.enable = 'Y' ");
		
		if(!CheckClass.isBlank(MODELNAME)){
			whereSql.append(" and t.MODELNAME = :MODELNAME");
			params.put("MODELNAME", MODELNAME);
		}
		if(REFCODE_list.size() > 0){
			whereSql.append(" and t.REFCODE in (:REFCODE_list)");
			params.put("REFCODE_list", REFCODE_list);
		}
		
		int page = NumberUtils.toInt((String)map.get("page"));
		int rows = NumberUtils.toInt((String)map.get("rows"));
		int start = (page-1)*rows;
		PageVo pageVo = new PageVo();
		List rowsList = this.queryEntitesByPageForSql(start, rows,selectSql.append(pageSql).append(whereSql).append(" order by t.REMARK asc ").toString(), params,BPSAEXLM.class);
		int total = this.getEntitiesCountForSql(pageSql.append(whereSql).toString(), params);
		pageVo.setTotal(total);
		pageVo.setRows(rowsList);
		return pageVo;
	}
	
}

 

导出列表的建表语句

-- Create table
create table BPSAEXLM
(
  refcode     NUMBER(10) default 0 not null,
  modelname   NVARCHAR2(100) not null,
  colname     NVARCHAR2(100) not null,
  colcode     NVARCHAR2(100) not null,
  coltype     NVARCHAR2(100),
  colfarmat   NVARCHAR2(100),
  enable      CHAR(1),
  remark      NVARCHAR2(200),
  lastmoduser NVARCHAR2(20),
  lastmoddate DATE
)
tablespace HEAD
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );
-- Create/Recreate primary, unique and foreign key constraints 
alter table BPSAEXLM
  add constraint PK_BPSAEXLM primary key (REFCODE)
  using index 
  tablespace HEAD
  pctfree 10
  initrans 2
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );

 

你可能感兴趣的:(excel,反射)