Through the Spring reflection mechanism, realize the general Excel export class

Struts2.xml

<!-- Basic data settings-->
	<package name="exportExcel" namespace="/exportExcel" extends="default">
		 <!-- Attachment information-->
		 <default-class-ref class="com.microcredit.common.action.ExportExcelAction">
		 </default-class-ref>
		 
		 <!-- Query export Excel column configuration table-->
		 <action name="getColumnsByPage" method="getColumnsByPage">
			 <result type="json">
			   <param name="root">pageVo</param>
			 </result>
		 </action>
		 
		 <!-- Export Excel-->
		 <action name="getDownloadExcel" method="getDownloadExcel">
			<result name="excel" type="stream">
			    <param name="contentType">application/vnd.ms-excel</param>
			    <param name="inputName">inputStreamExcel</param>
			    <param name="contentDisposition">attachment;filename="${fileName}"</param>
			    <param name="bufferSize">1024</param>
			</result>
        </action>
	</package>

 

 

Export Excel tool Jsp

exportexcel.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>导出excel</title>
    <script type="text/javascript">
    $(function(){
    	
		$("#open_win_excelGrid").click(function(){
			$("#win_excelGrid").window('open');
			$("#win_excelGrid").window('center');
			//Load excel to export datagrid
			$("#excelGrid").datagrid({
				  url:ctx + '/exportExcel/getColumnsByPage.do?MODELNAME=' + $("#MODELNAME").val(),//Provide module name
				  pagination:true,
				  idField:'REFCODE',
				  loadMsg:'Loading...',
				  singleSelect:false,
				  fitColumns:true,
				  striped:false,
				  border:false,
				  fit:true,
				  pageSize:10,
				  pageList:[10,15,20],
				  columns:[[
				     {checkbox:true,field:'check', width:100},
		             {title:'Column name',field:'COLNAME', width:120, align:'center'}
				 ]]
			});
		});
		
		//Download Excel
		$("#downloadExcel").click(function(){
			var serviceName = $("#SERVICENAME").val();
			var methodName = $("#METHODNAME").val();
			var MODELNAME = $("#MODELNAME").val();
			var excelName = $("#EXCELNAME").val();
			var sheetName = $("#SHEETNAME").val();
			var title = $("#TITLE").val();
			var seledGrid = $ ('# excelGrid'). datagrid ('getSelections');
			if(seledGrid.length > 0){
				var refcodeParams = new Array();
				for (i = 0; i < seledGrid.length; i++) {
					refcodeParams[i] = seledGrid[i].REFCODE;
				};
				
				var url = "/exportExcel/getDownloadExcel.do?1=1";
					url += "&serviceName=" + serviceName,//bean名
					url += "&methodName=" + methodName,//方法名
					url += "&MODELNAME=" + MODELNAME,//module name
					url += "&excelName=" + excelName;
					url += "&sheetName=" + sheetName;
					url += "&title=" + title;
					url += "&refcodeParams[]=" + refcodeParams;
					url += "&queryParams=" + JSON.stringify(queryParams);
				
				var form=$("<form>");//Define a form
				form.attr("style","display:none");
				form.attr("target","");
				form.attr("method","post");
				form.attr("action",ctx + url);
				$("body").append(form);//Place the form in the web
				form.submit();
				$(".btnExcelBack").click();
			} else {
				$.messager.alert('Prompt','Please select the column to download!','info');
				return false;
			}
		});
		
		$(".btnExcelBack").click(function(){
			$("#win_excelGrid").window('close');
			$('#excelGrid').datagrid('clearSelections');
		});
		
    });
    </script>
</head>
<body>
	<div id="win_excelGrid" class="easyui-window" title="导出Excel" style="width:480px;height:385px"  
		data-options="modal:true,closed:true,resizable:false">
		<div id="cc" class="easyui-layout" fit="true">   
		    <div data-options="region:'center'" style="padding:2px;background:#eee;">
		    	<table id="excelGrid" toolbar='#northPanel'></table>
		    </div>   
		    <div data-options="region:'south'" style="padding:3px;background:#eee;height:35px">
		    	<div align="center">
	            	<a id="downloadExcel" href="javascript:void(0)" class="easyui-linkbutton"
						data-options="iconCls:'icon-ok'" style="width: 80px">下载</a>
		            <a href="javascript:void(0)" class="easyui-linkbutton btnExcelBack"
						data-options="iconCls:'icon-undo'" style="width: 80px">返回</a>
				</div>
		    </div>   
		</div>  
	</div>
</body>
</html>

 

 

The report page needs to introduce the Excel export tool Jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@include file="/common/in.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Post-loan query</title>
</head>
<body>
    <table id="qryDataGrid"></table>
    <div id="qyNorthPanel">
        <div align='center'>
            <a id="btnQuery" href="javascript:void(0)" style="width: 80px"
                class="easyui-linkbutton" data-options="iconCls:'icon-search'">查询</a>
            <span class="btnSplit"></span>
            <a id="open_win_excelGrid" href="javascript:void(0)" style="width: 100px"
                class="easyui-linkbutton" data-options="iconCls:'icon-print'">导出Excel</a>
            <span class="btnSplit"></span>
        </div>
    </div>
    <input type="hidden" id="SERVICENAME" value="loanQryInfoService" />
    <input type="hidden" id="METHODNAME" value="getLoanQryByPage" />
    <input type="hidden" id="MODELNAME" value="LOANFQRY" />
    <input type="hidden" id="EXCELNAME" value="贷后查询Excel" />
    <input type="hidden" id="SHEETNAME" value="贷后查询" />
    <input type="hidden" id="TITLE" value="贷后查询" />
    <%@include file="/common/exportexcel.jsp"%>
</body>
</html>

 

 

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;
	
	//Inject the corresponding 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;
	}
	
	/**
	 * Export Excel list	
	 * @return
	 */
	public String getDownloadExcel(){

		//Get Excel name, header, title
		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")));
		
		//retrieve data
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		try {
			this.getRequestMap().put("userId", this.getCurrentUser().getUSERID());
			dataList = this.exportExcelService.getDownExportExcelData(getRequestMap());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		//get list data
		try {
			pageVo = this.exportExcelService.getExportExcelByPage(getRequestMap());
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			this.getOpearteFailException(e);
		}
		List<BPSAEXLM> BPSAEXLMList = pageVo.getRows();//--- no corresponding entity

		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[]{"Export Eecel exception!"},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<Map<String,Object>> 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"));
		
		//Get through SpringUtils, the corresponding bean object
		Object infoService = springUtils.beanFactory.getBean(serviceName);
		//Get the method object through the service created by the bean object and the known method name
		Method method = ReflectUtils.findDeclaredMethod(infoService.getClass(),methodName, new Class[]{Map.class});
		Map queryMap = (Map)JSONObject.fromObject(queryParams);
		queryMap.put("userId", userId);
		//Execute the method, pass the created service object and the required parameters of the method
		Object obj = method.invoke(infoService, queryMap);
		
		PageVo pageVo = new PageVo();
		if(obj instanceof PageVo){
			pageVo = (PageVo) obj;
		}
		List<Map<String,Object>> 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);
	//	
	// //The query condition needs to bring the parameters of the paging
	//	
	//	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){
	// //Using paging query, you need to loop query paging, the results of each page query are spliced ​​into a 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<String> REFCODE_list = new ArrayList<String>();
		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 statement for export list

-- 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
  );

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326564942&siteId=291194637
Recommended