关闭

Excel大量导出

标签: POIjavaexcel大量导出
1040人阅读 评论(0) 收藏 举报
分类:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>exampleDome</groupId>
	<artifactId>exampleDome</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.2.6.RELEASE</spring.version>
		<slf4j.version>1.7.8</slf4j.version>
		<logback.version>1.1.2</logback.version>
		<jackson.version>2.4.4</jackson.version>
		<aspectj.version>1.8.4</aspectj.version>
		<jdbc.driver.groupId>mysql</jdbc.driver.groupId>
		<jdbc.driver.artifactId>mysql-connector-java</jdbc.driver.artifactId>
		<jdbc.driver.version>5.1.22</jdbc.driver.version>
		<mybatis.version>3.2.7</mybatis.version>
		<easypoi.version>2.3.0.2</easypoi.version>
		<commons-io.version>2.4</commons-io.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- spring aop -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${aspectj.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>${aspectj.version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>
		<!-- 代码直接调用log4j会被桥接到slf4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>log4j-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
			<scope>runtime</scope>
		</dependency>
		<!-- 代码直接调用common-logging会被桥接到slf4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
			<scope>runtime</scope>
		</dependency>
		<!-- 代码直接调用java.util.logging会被桥接到slf4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jul-to-slf4j</artifactId>
			<version>${slf4j.version}</version>
			<scope>runtime</scope>
		</dependency>
		<!-- JSON begin -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.module</groupId>
			<artifactId>jackson-module-jaxb-annotations</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<!-- JSON end -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		
		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
		
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.18</version>
		</dependency>
		<dependency>
			<groupId>${jdbc.driver.groupId}</groupId>
			<artifactId>${jdbc.driver.artifactId}</artifactId>
			<version>${jdbc.driver.version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		
		
		
		 <dependency>
            <groupId>org.jeecg</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>${easypoi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jeecg</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>${easypoi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jeecg</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>${easypoi.version}</version>
        </dependency>
        <dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>${commons-io.version}</version>
		</dependency>
	</dependencies>
</project>


package com.main.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 处理有关IO的帮助类
 */
public class IOUtils extends org.apache.commons.io.IOUtils {			
	
	private static Logger logger=LoggerFactory.getLogger(IOUtils.class);
	/**
	 * 中文文件名称乱码修复
	 * @param fileName
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	private static final HttpHeaders getUTF8FileNameInHeaders(String fileName) throws UnsupportedEncodingException{
		HttpHeaders headers = new HttpHeaders();
		fileName = URLEncoder.encode(fileName, "UTF-8");
        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + fileName + "\"");
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
		return headers;
	}
	/**
	 * 封装图片流方法
	 */
	public static ResponseEntity<byte[]> getResponseEntity(HttpServletRequest request,BufferedImage image,String fileName){
		
		ResponseEntity<byte[]> responEntity = null ;
		try {
			HttpHeaders headers = getUTF8FileNameInHeaders(fileName);
			ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(byteOut);
			encoder.encode(image); 
			responEntity = new ResponseEntity<byte[]>(byteOut.toByteArray(),headers, HttpStatus.OK);
		} catch (IOException e) {
			logger.error("封装图片出现异常!",e);
		} 
		return responEntity ;
	} 
	/**
	 * 封装文件方法
	 */
	public static ResponseEntity<byte[]> getResponseEntity(HttpServletRequest request,String fileName,String filePath){
		ResponseEntity<byte[]> responEntity = null ;
		try {
			HttpHeaders headers = getUTF8FileNameInHeaders(fileName);   
			responEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(filePath)),headers, HttpStatus.OK);
		} catch (IOException e) {
			logger.error("导出封装数据出现异常!",e);
		} 
		return responEntity ;
	} 
}


package com.main.utils;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

public class ExcelUtil {
	protected static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
	private static  final int SHEET_MAX_COUNT = 0xFFFF ;/**Excel的每个sheet所包含数据的最大行数***/
	/**
	 * 导出Excel的原数据页
	 * @author lixin
	 *
	 */

	private static HSSFWorkbook createExcel(OutputStream fileOut){
		HSSFWorkbook workbook = new HSSFWorkbook();
		return workbook;
	}
	/**
	 * 写入excel
	 * @param workbook
	 * @param out
	 */
	private static void writeExcel(HSSFWorkbook workbook,OutputStream fileOut){
		try {
	        workbook.write(fileOut);
	        fileOut.flush();
	     } catch (IOException e) {
	        e.printStackTrace();
	     }	 
	}
	/**
	 * 关闭流
	 * @param out
	 */
	private static void closeExcel(OutputStream fileOut){
		if (fileOut != null) {
			try {
				fileOut.flush();
				fileOut.close();
			} catch (IOException e) {
			}
			fileOut = null;
		}
	}
	
	/**
	 * 创建sheet和表头
	 * @param workbook
	 * @param headers
	 * @return
	 */
	private static HSSFSheet createSheetAndSetHeads(HSSFWorkbook workbook,String [] headers,OutputStream fileOut){
		  // 生成一个表格
	      HSSFSheet sheet = workbook.createSheet("第"+(workbook.getNumberOfSheets()+1)+"页");

	      // 设置表格默认列宽度为15个字节
	      sheet.setDefaultColumnWidth((short) 15);

	      // 生成一个样式
	      HSSFCellStyle style = workbook.createCellStyle();

	      // 设置这些样式
	      style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
	      style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
	      style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
	      style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
	      style.setBorderRight(HSSFCellStyle.BORDER_THIN);
	      style.setBorderTop(HSSFCellStyle.BORDER_THIN);
	      style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

	      // 生成一个字体
	      HSSFFont font = workbook.createFont();
	      font.setColor(HSSFColor.VIOLET.index);
	      font.setFontHeightInPoints((short) 12);
	      font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

	      // 把字体应用到当前的样式
	      style.setFont(font);
	      
	      HSSFRow row = sheet.createRow(0);

	      for (short i = 0; i < headers.length; i++) {

	         HSSFCell cell = row.createCell(i);
	         cell.setCellStyle(style);
	         HSSFRichTextString text = new HSSFRichTextString(headers[i]);
	         cell.setCellValue(text);

	      }
	      return sheet;
	}
	

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 插入到excel
	 * @param sheet
	 * @param cols
	 * @param esdp
	 * @param esdpBeginIndex
	 * @param esdpEndIndex
	 */
	private static void insertExcelBody(HSSFWorkbook workbook,HSSFSheet sheet,String[] cols,List<Map<String,Object>> esdp,int esdpBeginIndex,int esdpEndIndex){
		if(esdp == null){
			return;
		}
		// 生成并设置另一个样式
		HSSFCellStyle style2 = workbook.createCellStyle();
		
		style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
		style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		
		// 生成另一个字体
		HSSFFont font2 = workbook.createFont();
		font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

		// 把字体应用到当前的样式
		style2.setFont(font2);
		HSSFFont font3 = workbook.createFont();
		for(int j=esdpBeginIndex; j < esdpEndIndex ; j++){
			HSSFRow row = sheet.createRow(sheet.getLastRowNum()+1);
			Map<String,Object> map = (Map<String,Object>)(esdp.get(j));
			for (int i=0; i<cols.length; i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellStyle(style2);
				Object value= map.containsKey(cols[i])? map.get(cols[i]):"" ; 
				
				String textValue = null;  
				if (value instanceof Date) {
					Date date = (Date) value;
				    textValue = sdf.format(date);
				}else{
					  //其它数据类型都当作字符串简单处理
				      textValue = value.toString();
				}
				
				 //利用正则表达式判断textValue是否全部由数字组成
				 if(textValue!=null){
				     Pattern p = Pattern.compile("^//d+(//.//d+)?$");  
				     Matcher matcher = p.matcher(textValue);
					 if(matcher.matches()){
					    //是数字当作double处理
					    cell.setCellValue(Double.parseDouble(textValue));
					 }else{
			            HSSFRichTextString richString = new HSSFRichTextString(textValue);
			            font3.setColor(HSSFColor.BLUE.index);
			            richString.applyFont(font3);
			            cell.setCellValue(richString);
					 }
				 }
	        }  //for
		}
	}
	
	/**
	 * 将元数据转换并写入excel文件
	 * @param headers
	 * @param cols
	 * @param workbook
	 * @param esdp
	 * @param fileOut
	 */
	private static void convert数据源ToExcelFile(String [] headers,String[] cols,HSSFWorkbook workbook,List<Map<String,Object>> esdp,OutputStream fileOut){
		if(workbook == null || esdp == null || esdp.size() == 0){
			return;
		}
		HSSFSheet currtSheet = null;
		int  currtBeginIndex = 0;//当前插入表的元数据开始索引
		int  currtMaxCount =  esdp.size();//当前插入表的元数据最大记录
		int  currtSurplusCount = currtMaxCount;//记录剩余记录数量
		
		
		while(currtSurplusCount > 0){
			//计算当前excelsheet没有或当前sheet记录数量等于最大记录数量就创建,否则获取最后一个sheet
			if(workbook.getNumberOfSheets() == 0 || workbook.getSheetAt(workbook.getNumberOfSheets() - 1).getLastRowNum() >= SHEET_MAX_COUNT){
				currtSheet = createSheetAndSetHeads(workbook,headers,fileOut);
			}
			//若没创建就获取最后一个sheet
			if(currtSheet == null){
				currtSheet = workbook.getSheetAt(workbook.getNumberOfSheets() - 1);
			} 
			//获取能插入sheet最大数据记录
			if(SHEET_MAX_COUNT - currtSheet.getLastRowNum() < currtMaxCount){
				currtMaxCount = SHEET_MAX_COUNT - currtSheet.getLastRowNum();
			}
			//获取元数据当前结束索引
			int currtEndIndex = currtBeginIndex+currtMaxCount;
			//插入记录
			insertExcelBody(workbook,currtSheet,cols,esdp,currtBeginIndex,currtEndIndex);
			//设置下当前元素插入的下一个开始索引
			currtBeginIndex = currtEndIndex;
			//计算剩余记录数量
			currtSurplusCount -= currtMaxCount;
			currtMaxCount = currtSurplusCount;
		}
	}
	
	/**
	 * 导出Excel
	 * @param headers
	 * @param cols
	 * @param file
	 * @param service
	 * @param getResultsMethodName
	 * @param pageNumKeyOrIndex
	 * @param pageSizeKeyOrIndex
	 * @param getResultsMethodParams
	 * @throws FileNotFoundException
	 */
	public static void exportExcel(String[] headers,String[] cols,File file,Object service,String getResultsMethodName,Object pageNumKeyOrIndex,Object pageSizeKeyOrIndex,Object ... getResultsMethodParams) throws FileNotFoundException{
		OutputStream fileOut = new FileOutputStream(file);//excel文件路径
	  	try {
			HSSFWorkbook workbook = createExcel(fileOut);// 声明一个工作薄
			//-------------读写数据begin
			
			//获取参数类型
			Class<?>[] parameterTypes = new Class<?>[getResultsMethodParams.length];
			
			for (int i = 0; i < getResultsMethodParams.length; i++) {
				parameterTypes[i]=getResultsMethodParams[i].getClass();
			}
			
			//获取参数列表,用于修改翻页参数
			Map paramsMap = null;
			Integer pageNumIndex = -1;
			Integer pageSizeIndex = -1;
			if(getResultsMethodParams.length == 1 && pageNumKeyOrIndex instanceof String && pageSizeKeyOrIndex instanceof String){
				Object paramsO = getResultsMethodParams[0];
				if(paramsO instanceof Map && ((Map)paramsO).containsKey(pageNumKeyOrIndex) && ((Map)paramsO).containsKey(pageSizeKeyOrIndex)){
					paramsMap = ((Map) paramsO);
				}
			}else if(pageNumKeyOrIndex instanceof Integer && pageSizeKeyOrIndex instanceof Integer){
				pageNumIndex = (Integer) pageNumKeyOrIndex;
				if(pageNumIndex < 0 || pageNumIndex >= getResultsMethodParams.length){
					pageNumIndex = -1;
				}
				pageSizeIndex = (Integer) pageSizeKeyOrIndex;
				if(pageSizeIndex < 0){
					pageSizeIndex = -1;
					pageSizeIndex = -1;
				}
			}
			
			
			//获取方法
			Method  m = service.getClass().getMethod(getResultsMethodName,parameterTypes);
			
			//获取数据
			Object o = null; List<Map<String,Object>> esdp = null;
			while ((o = m.invoke(service, getResultsMethodParams))!=null && (esdp = (List<Map<String,Object>>)o) != null && esdp.size() > 0){
				convert数据源ToExcelFile( headers, cols, workbook, esdp, fileOut);
				//计算下一页查询参数
				if(paramsMap != null){
					paramsMap.put(pageNumKeyOrIndex, ((Integer)paramsMap.get(pageNumKeyOrIndex))+((Integer)paramsMap.get(pageSizeKeyOrIndex)));
				}else if(pageNumIndex >= 0){
					getResultsMethodParams[pageNumIndex] = ((Integer)getResultsMethodParams[pageSizeIndex]) + ((Integer)getResultsMethodParams[pageNumIndex]);
				}else{
					break;
				}
				
			}
			//-------------读写数据end
			writeExcel(workbook,fileOut);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			closeExcel(fileOut);//关闭文件流
		}
	}
	/**
	 * 导出Excel
	 * @param request
	 * @param response
	 * @param headerNames //表头标题
	 * @param colNames //对应数据源中的数据键值
	 * @param service //获取数据源数据的service实例
	 * @param getResultsMethodName //获取数据源数据service对应的方法
	 * @param pageNumKeyOrIndex //查询时sql分页起始索引键值不给就是当前页,如果方法参数是map类型就传key,如果是一般数据类就传在数据类型数据中的索引值
	 * @param pageSizeKeyOrIndex //查询时sql每页数量键值不给就是只查当前页,如果方法参数是map类型就传key,如果是一般数据类就传在数据类型数据中的索引值
	 * @param getResultsMethodParams //获取数据源数据service对应方法的对应参数
	 * @return
	 */
	public static File getExportExcelFileData(HttpServletRequest request,HttpServletResponse response,
				String[] headerNames,String[] colNames,Object service,String getResultsMethodName,Object pageNumKeyOrIndex,Object pageSizeKeyOrIndex,Object ... getResultsMethodParams){
		// 生成要导出的文件
		String path = request.getSession().getServletContext().getRealPath(File.separator) + "upload"+File.separator;
		File filePath = new File(path);
		if (!filePath.exists()) {
			filePath.mkdir();
		}
		File destFile = new File(filePath,UUID.randomUUID()+"");
		try {
			exportExcel( headerNames, colNames, destFile, service, getResultsMethodName, pageNumKeyOrIndex , pageSizeKeyOrIndex, getResultsMethodParams);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return destFile;
		
	}

	/**
	 * 文件转换字节流
	 * @param response
	 * @param request
	 * @param file
	 * @return
	 */
	public static ResponseEntity<byte[]> getFileBytes(HttpServletResponse response,HttpServletRequest request,String outFileName,File file){
		if (!file.exists() || !file.canRead()) {
	          response.setContentType("text/html;charset=utf-8");
	          try {
				response.getWriter().write("您下载的文件不存在!");
			} catch (IOException e) {
				e.printStackTrace();
			}
	          return null;
	    }
		// 获取导出信息
		ResponseEntity<byte[]> exportData = IOUtils.getResponseEntity(request,outFileName, file.getAbsolutePath());
		// 删除生成的导出文件
		file.delete();
		
		return exportData;
	}
	
}

package com.main.controller.font;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.main.services.font.UserDetailService;
import com.main.utils.ExcelUtil;

@Controller
@RequestMapping("/test")
public class TestController {
	@Autowired
	private UserDetailService userDetailService;
	@RequestMapping("")
	@ResponseBody
	public Object index() throws Exception{
		Object params [] = new Object[]{0,10};
		Class<?>[] parameterTypes = new Class<?>[params.length];
		for (int i = 0; i < params.length; i++) {
			parameterTypes[i]=params[i].getClass();
		}
		Method  m = userDetailService.getClass().getMethod("querList",parameterTypes);
		
		return m.invoke(userDetailService, params);//userDetailService.querList(0,10);
	}
	@RequestMapping("/export")
	public ResponseEntity<byte[]> export(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String [] headerNames = {
			"列表标题1","列表标题2"
		};
		String [] colNames = {
			"mapKey1","mapKey2"
		};
		File file = ExcelUtil.getExportExcelFileData(request, response, headerNames, colNames, userDetailService, "querList", 0, 1,0,1000);
		return ExcelUtil.getFileBytes(response, request, "我的文件.xls",file);
	}
}



1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14417次
    • 积分:273
    • 等级:
    • 排名:千里之外
    • 原创:11篇
    • 转载:2篇
    • 译文:0篇
    • 评论:19条
    最新评论