`

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

    博客分类:
  • Java
阅读更多

Struts2.xml

<!-- 基本资料设置 -->
	<package name="exportExcel" namespace="/exportExcel" extends="default">
		 <!-- 附件信息  -->
		 <default-class-ref class="com.microcredit.common.action.ExportExcelAction">
		 </default-class-ref>
		 
		 <!-- 查询导出Excel列配置表-->
		 <action name="getColumnsByPage" method="getColumnsByPage">
			 <result type="json">
			   <param name="root">pageVo</param>
			 </result>
		 </action>
		 
		 <!-- 导出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>

 

 

导出Excel的工具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');
			//加载excel导出datagrid
			$("#excelGrid").datagrid({
				  url:ctx + '/exportExcel/getColumnsByPage.do?MODELNAME=' + $("#MODELNAME").val(),//提供模块名
				  pagination:true,
				  idField:'REFCODE',
				  loadMsg:'加载中...',
				  singleSelect:false,
				  fitColumns:true,
				  striped:false,
				  border:false,
				  fit:true,
				  pageSize:10,
				  pageList:[10,15,20],
				  columns:[[
				     {checkbox:true,field:'check', width:100},
		             {title:'列名称',field:'COLNAME', width:120, align:'center'}
				 ]] 
			});
		});
		
		//下载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,//模块名
					url += "&excelName=" + excelName;
					url += "&sheetName=" + sheetName;
					url += "&title=" + title;
					url += "&refcodeParams[]=" + refcodeParams;
					url += "&queryParams=" + JSON.stringify(queryParams);
				
				var form=$("<form>");//定义一个form表单
				form.attr("style","display:none");
				form.attr("target","");
				form.attr("method","post");
				form.attr("action",ctx + url);
				$("body").append(form);//将表单放置在web中
				form.submit();
				$(".btnExcelBack").click();
			} else {
				$.messager.alert('提示','请选择要下载的列!','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>

 

 

报表页面需要引入  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"%>
<!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>贷后查询</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;
	
	//注入相应的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<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();
		}
		
		//获取列表数据
		try {
			pageVo = this.exportExcelService.getExportExcelByPage(getRequestMap());
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			this.getOpearteFailException(e);
		}
		List<BPSAEXLM> 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<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"));
		
		//通过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<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);
	//	
	//	//查询条件需要带入分页的参数
	//	
	//	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<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
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
  );

 

分享到:
评论

相关推荐

    C#通用Excel导入导出工具类

    本篇文章将深入探讨“C#通用Excel导入导出工具类”的实现原理及应用,主要涉及的技术点包括反射、特性以及如何创建一个高效的Excel导入导出解决方案。 首先,我们要理解反射在C#中的作用。反射是一种强大的机制,它...

    Spring Boot中实现列表数据导出为Excel文件

    通过本文的学习,我们了解了如何使用Apache POI库在Spring Boot项目中实现列表数据导出为Excel文件的功能。这种方法不仅提高了工作效率,也为数据分析和报告制作提供了极大的便利。希望本文能帮助您更好地理解和应用...

    使用Springboot实现excel的导入导出

    在Spring Boot中实现Excel的导入导出可以通过POI库来实现,POI是一个开源的Java库,用于处理Microsoft Office格式文件,包括Excel。一个简单的示例,演示如何在Spring Boot项目中使用POI来实现Excel的导入导出功能。...

    spring boot excel导出

    spring boot excel导出 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过...

    Jett+Spring MVC实现Excel导出

    通过以上步骤,我们就可以在Spring MVC应用中集成Jett,实现动态生成和导出Excel文件的功能。这不仅可以提高用户体验,也有利于数据的管理和分析。如果你需要更多关于Jett和Spring MVC的详细信息,可以参考我的CSDN...

    spring ext 日志管理和导出excel

    在“spring ext 日志管理和导出excel”这个主题中,我们将深入探讨如何利用Spring扩展功能来实现日志管理以及Excel数据导出。 首先,日志管理是任何应用程序的基础部分,它帮助开发者跟踪系统行为、调试问题并记录...

    Jxls+Spring MVC实现Excel导出

    "Jxls+Spring MVC实现Excel导出"的主题聚焦于如何利用Jxls库和Spring MVC框架来实现这一功能。Jxls是一个强大的Java库,它扩展了Apache POI,使得在Excel模板上进行编程变得简单,而Spring MVC是Spring框架的一部分...

    spring boot+mybatis plus+easy poi实现数据库导出成excel和excel导入到数据库.zip

    在本项目中,"spring boot+mybatis plus+easy poi实现数据库导出成excel和excel导入到数据库",开发者利用了Spring Boot、MyBatis Plus和EasyPoi库来实现了一个功能强大的数据交互系统,允许用户将数据库中的数据...

    Spring框架实现Excel批量导入数据

    本教程将详细讲解如何利用Spring框架实现Excel数据的批量导入,以提高数据录入效率。 首先,我们需要了解Excel文件的结构。Excel是一种常用的电子表格软件,它的数据通常存储在工作簿(Workbook)中,每个工作簿...

    struts2+hibernate+spring+jfreechart+导出excel+导出pdf完美整合.zip

    这个压缩包文件“struts2+hibernate+spring+jfreechart+导出excel+导出pdf完美整合.zip”显然是一个整合了这些技术的示例项目,用于演示如何在实际开发中实现数据处理、视图展示以及文件导出功能。 首先,Struts2 ...

    Spring3 MVC + POI 实现 Excel与MySQL 的导入导出

    综上所述,Spring3 MVC + POI 实现 Excel与MySQL 的导入导出是企业级应用中的常见技术组合,通过合理的设计和实现,可以有效地提高数据处理的效率和灵活性。开发者应当熟练掌握Spring MVC的控制器设计、服务层业务...

    基于spring的以excel模板的导入导出

    通过以上步骤,你可以在Spring应用中实现基于Excel模板的导入导出功能,从而提高工作效率,简化用户界面,同时保持数据的一致性和规范性。这是一项实用且常见的功能,广泛应用于数据分析、报表生成和数据交换等场景...

    使用Spring事件机制实现异步的方法

    使用Spring事件机制实现异步的方法 Spring框架提供了一种事件机制,允许开发者将代码解耦合,实现松散耦合的设计理念。这里将详细介绍如何使用Spring事件机制实现异步的方法。 事件机制的实现主要包括三个部分:...

    java实现Excel导入导出

    Java 实现 Excel 导入导出 ...在 Struts2+Spring 框架中实现 Excel 导入导出需要使用 POI 库来读取和写入 Excel 文件中的数据,并对数据进行处理。使用 POI 库可以简化 Excel 文件的操作,并提高程序的性能。

    spring MVC 导出excel

    Spring MVC 是一个强大的Java web开发框架,用于构建可维护、高性能和灵活的Web应用程序。在“spring MVC 导出excel...通过不断实践和优化,Spring MVC结合Apache POI可以实现功能强大且用户体验良好的Excel导出功能。

    spring导出Excel

    本篇文章将深入探讨如何使用Spring Boot结合jxl库实现Excel文件的生成与导出,以及如何自定义标题列。 首先,让我们了解Excel文件的基本概念。Excel是一种电子表格程序,由Microsoft Office提供,广泛用于数据存储...

    反射实现 AOP 动态代理模式(Spring AOP 的实现原理)

    在使用反射实现AOP动态代理时,我们也需要注意一些问题。例如,由于代理类是在运行时动态创建的,这可能会影响程序的性能,特别是在频繁调用代理方法的情况下。因此,在实际开发中,需要根据应用场景的性能要求和...

    Springboot+Poi实现Excel的导入导出

    本项目结合了Spring Boot和POI,实现了Excel文件的导入与导出功能,这在数据管理、报表生成、数据分析等领域十分常见。 首先,我们要理解Spring Boot如何与MyBatis集成来处理数据库操作。MyBatis是一个轻量级的持久...

    spring boot2快速导出excel的java工具类demo源码:export-excel

    spring boot2快速导出excel的示例源码 操作系统:windows10 JAVA jdk:1.8 开发工具:IDEA java架构:spring boot 2.1.6 gitHub:https://github.com/cn-h-jar/exportexcel 作者:jar 运行提示: 启动项目...

    Excel 导出 struts2 spring hibernate

    标题 "Excel 导出 struts2 spring hibernate" 暗示了这是一个关于使用Java Web开发框架Struts2、Spring和Hibernate实现Excel数据导入导出的教程或项目。这三个框架是Java后端开发中常见的技术栈,Struts2用于控制...

Global site tag (gtag.js) - Google Analytics