精华内容
下载资源
问答
  • java导出Excel工具类

    2018-09-17 19:07:46
    java导出Excel工具类,支持web导出,xls以及xlsx导出。可完美运行,
  • java导出excel工具类

    千次阅读 2016-04-18 15:19:46
    java导出excel需要使用HSSFWorkbook这个类,需要导入poi-3.6-20091214.jar 工具类调用如下:package com.qlwb.business.util;import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder...

    java导出excel需要使用HSSFWorkbook这个类,需要导入poi-3.6-20091214.jar
    工具类调用如下:

    package com.qlwb.business.util;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.URLEncoder;
    import java.util.List;
    
    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.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.util.HSSFColor;
    import org.apache.poi.ss.util.CellRangeAddress;
    
    /**
     * 导出报表的公共类,提供公共的导出报表的方法
     * @Copyright: Copyright (c) 2015
     * @Company: 
     * @author 鹿伟伟
     * 
     */
    public class ExportExcel {
    
        static boolean tempDirflag1 = true;
        static boolean tempDirflag2 = true;
    
        /**
         * 根据传入的集合数据生成报表的方法
         * 
         * @param list
         *            报表标题表头及数据封装的list,格式:list的第一条数据是标题,String类型;第二条数据是表头列表,List类型;从第三条开始是数据列表
         *            ,List类型
         * @param filename
         *            报表excel的文件名,不需要扩展名
         * @param response
         *            HttpServletResponse
         * @return 1表示成功 0表示失败
         * @throws IOException
         * @Create luweiwei 2015-08-18
         * @change 
         */
        @SuppressWarnings("unchecked")
        public static int createReport(List<Object> list, String filename,
                HttpServletResponse response) throws IOException {
    
            // 数据list至少包括标题和表头
            if (list.size() < 2) {
                return 0;
            }
    
            // 组装excel
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
    
            // 设置Excel标题字体和样式
            HSSFFont headFont = workbook.createFont();
            headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            headFont.setFontHeightInPoints((short) 20);
            HSSFCellStyle headCellStyle = workbook.createCellStyle();
            headCellStyle.setFont(headFont);
            // headCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            // headCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            // headCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            // headCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            headCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            headCellStyle.setWrapText(true);
            headCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            // headCellStyle.setFillForegroundColor(GREEN_COLOR);
    
            // 设置Excel表头的字体和样式
            HSSFFont thfont = workbook.createFont();
            thfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            HSSFCellStyle thCellStyle = workbook.createCellStyle();
            thCellStyle.setFont(thfont);
            thCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            thCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            thCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            thCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            thCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            thCellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
            thCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    
            // 设置Excel内容的字体和样式
            HSSFFont font = workbook.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
            HSSFCellStyle titleCellStyle = workbook.createCellStyle();
            titleCellStyle.setFont(font);
            titleCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            titleCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            titleCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            titleCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            titleCellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
            // titleCellStyle.setFillForegroundColor(GREEN_COLOR);
    
            // 单元格居左样式
            HSSFCellStyle cellLeft = null;
    
            // 单元格居中样式
            HSSFCellStyle cellCenter = null;
    
            // 单元格居右样式
            HSSFCellStyle cellRight = null;
    
            // 单元格居左样式
            cellLeft = workbook.createCellStyle();
            cellLeft.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellLeft.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellLeft.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellLeft.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellLeft.setAlignment(HSSFCellStyle.ALIGN_LEFT);
    
            // 单元格居中样式
            cellCenter = workbook.createCellStyle();
            cellCenter.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellCenter.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellCenter.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellCenter.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellCenter.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    
            // 单元格居右样式
            cellRight = workbook.createCellStyle();
            cellRight.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellRight.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellRight.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellRight.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellRight.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    
            // 第一行
            // 合并标题单元格
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,
                    ((List<String>) list.get(1)).size() - 1));
            HSSFRow row = sheet.createRow(0);
            row.setHeightInPoints(40);
            HSSFCell cell = null;
            cell = row.createCell(0);
            cell.setCellStyle(headCellStyle);
            cell.setCellValue((String) (list.get(0)));
    
            // 设置表头单元格
            List<String> tmpList = null;
            tmpList = (List<String>) list.get(1);
            int rownum = sheet.getLastRowNum();
            row = sheet.createRow(rownum + 1);
            for (int i = 0; i < tmpList.size(); i++) {
                sheet.setColumnWidth(i, 6000);
                cell = row.createCell(i);
                cell.setCellStyle(thCellStyle);
                cell.setCellValue(tmpList.get(i));
            }
    
            // 循环设置数据的单元格
            for (int i = 2; i < list.size(); i++) {
                tmpList = (List<String>) list.get(i);
                rownum = sheet.getLastRowNum();
                row = sheet.createRow(rownum + 1);
                for (int j = 0; j < tmpList.size(); j++) {
                    cell = row.createCell(j);
                    cell.setCellStyle(titleCellStyle);
                    cell.setCellValue(tmpList.get(j));
                }
            }
            response.setHeader("Content-disposition", "attachment; filename="
                    + URLEncoder.encode(filename, "utf-8") + ".xls");
            response.setContentType("application/msexcel;charset=utf-8");
            OutputStream out = null;
            try {
                out = response.getOutputStream();
                out.flush();
                workbook.write(out);
            } finally {
                try {
                    if(out!=null){
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return 1;
        }
    }
    
    展开全文
  • Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类   ============================== ©Copyright 蕃薯耀 2017年9月13日 http://www.cnblogs.com/fanshuyao/   直接上代码: ...

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

     

    ==============================

    ©Copyright 蕃薯耀 2017年9月13日

    http://www.cnblogs.com/fanshuyao/

     

    直接上代码:

    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.math.BigDecimal;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    import javax.servlet.ServletOutputStream;
    
    import org.apache.commons.lang.StringUtils;
    
    public class ExportUtil {
    
    	/**
    	 * 只导出包含在includeFieldNames中的属性
    	 * @param sheetName 表格左下角的名称
    	 * @param firstRowTitle 第一行需要设置的title,为空则不设置
    	 * @param list 需要显示的数据集合
    	 * @param headers 表格属性列名数组
    	 * @param includeFieldNames 包含的实体属性
    	 * @param widths 列的宽度,不设置(为Null)则默认,设置则根据对应的列宽设置(可以是一个,可以是对应的数量,整形数字,如200)
    	 * @param outputStream 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
    	 * @param datetimePattern 时间形式,当为空(Null或空字符串)时默认为yyyy-MM-dd HH:mm:ss
    	 * @throws Exception
    	 */
    	@SuppressWarnings({ "unchecked", "rawtypes" })
    	public <T> void exportExcel(String sheetName, String firstRowTitle, List<T> list, String[] headers, String[] includeFieldNames, Integer[] widths,
    			ServletOutputStream outputStream, String datetimePattern) throws Exception {
    		
    		// 默认输出格式
    		if (StringUtils.isBlank(datetimePattern)) {
    			datetimePattern = "yyyy-MM-dd HH:mm:ss";
    		}
    		
    		// 创建一个excel应用文件
    		StringBuffer sb = new StringBuffer();
    		sb.append("<?xml version=\"1.0\"?>");
    		sb.append("\n");
    		sb.append("<?mso-application progid=\"Excel.Sheet\"?>");
    		sb.append("\n");
    		sb.append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
    		sb.append("\n");
    		sb.append(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
    		sb.append("\n");
    		sb.append(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
    		sb.append("\n");
    		sb.append(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
    		sb.append("\n");
    		sb.append(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
    		sb.append("\n");
    		
    		sb.append("<Styles>\n");
    		
    		/*设置列头样式*/
    		sb.append("<Style ss:ID=\"header\" ss:Name=\"header\">\n");//ss:ID=“header”对应下面的Row ss:StyleID=“header”
    		sb.append("<Interior ss:Color=\"#c4d79b\" ss:Pattern=\"Solid\"/>\n");// 设置背景颜色
    		sb.append("<Font ss:FontName=\"微软雅黑\" x:CharSet=\"134\" ss:Bold=\"Bolder\" ss:Size=\"12\"/>\n");//设置字体
    		sb.append("</Style>\n");
    		
    		/*其它默认样式设置*/
    		sb.append("<Style ss:ID=\"Default\" ss:Name=\"Normal\">\n");
    		//sb.append("<Alignment ss:Vertical=\"Center\"/>\n");
    		sb.append("<Alignment ss:Horizontal=\"Center\" ss:Vertical=\"Center\" ss:WrapText=\"1\"/>\n");// 左中右设置,一个是水平,一个是垂直
    		sb.append("<Borders>\n");
    		sb.append("<Border ss:Position=\"Left\" ss:LineStyle=\"Continuous\" ss:Color=\"#666\" ss:Weight=\"1\"/>\n");//左边框设置
    		sb.append("<Border ss:Position=\"Right\" ss:LineStyle=\"Continuous\" ss:Color=\"#666\" ss:Weight=\"1\"/>\n");//右边框设置
    		sb.append("<Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Color=\"#666\" ss:Weight=\"1\"/>\n");//下边框设置
    		sb.append("<Border ss:Position=\"Top\" ss:LineStyle=\"Continuous\" ss:Color=\"#666\" ss:Weight=\"1\"/>\n");//上边框设置
    		sb.append("</Borders>\n");
    		sb.append("<Font ss:FontName=\"宋体\" x:CharSet=\"134\" ss:Size=\"12\"/>\n");
    		sb.append("<Interior/>\n");
    		sb.append("<NumberFormat/>\n");
    		sb.append("<Protection/>\n");
    		sb.append("</Style>\n");
    		
    		sb.append("</Styles>\n");
    		
    		try {
    			
    			// 生成表格
    			int headersLength = headers.length;
    			
    			sb.append("<Worksheet ss:Name=\"" + sheetName + "\">");
    			sb.append("\n");
    			sb.append("<Table ss:ExpandedColumnCount=\"" + headersLength
    					+ "\" ss:ExpandedRowCount=\"1000000\" x:FullColumns=\"1\" x:FullRows=\"1\">");
    			sb.append("\n");
    			
    			if(!StrUtils.isEmptyArray(widths)){
    				if(widths.length > 1){
    					for (int i = 0; i < headersLength; i++) {
    						sb.append("<Column ss:AutoFitWidth=\"0\" ss:Width=\""+widths[i]+"\"/>");
    					}
    				}else{
    					for (int i = 0; i < headersLength; i++) {
    						sb.append("<Column ss:AutoFitWidth=\"0\" ss:Width=\""+widths[0]+"\"/>");
    					}
    				}
    			}
    			
    			
    			// 输出第一行的标题
    			if(!StrUtils.isBlank(firstRowTitle)){
    				//ss:StyleID可以加row或者Cell,加在Row,整行(包括空的Cell)都有,加上Cell,只有Cell才有。
    				sb.append("<Row  ss:Height=\"30\">");
    				sb.append("<Cell ss:StyleID=\"header\" ss:MergeAcross=\""+ (headersLength - 1)+"\"><Data ss:Type=\"String\">" + firstRowTitle + "</Data></Cell>");
    				sb.append("</Row>");
    			}
    			
    			// 输出列头
    			sb.append("<Row>");
    			for (int i = 0; i < headersLength; i++) {
    				sb.append("<Cell ss:StyleID=\"header\"><Data ss:Type=\"String\">" + headers[i] + "</Data></Cell>");
    			}
    			sb.append("</Row>");
    			
    			// 构建表体数据
    			for (int j = 0; j < list.size(); j++) {
    				
    				sb.append("<Row>");
    				
    				T t = (T) list.get(j);
    				
    				for (int i = 0; i < includeFieldNames.length; i++) {
    					
    					// 获取属性名称
    					String fieldName = includeFieldNames[i];
    					
    					String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    					
    					// 获取class对象
    					Class tCls = t.getClass();
    					
    					// 获取属性值
    					Object value = null;
    					
    					try {
    						// 获取class方法
    						Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
    						
    						// 获取属性值
    						value = getMethod.invoke(t, new Object[] {});
    						
    					} catch (NoSuchMethodException e) {
    						// 继续循环
    						continue;
    					}
    					
    					// 判断值的类型后进行强制类型转换
    					String textValue = "";
    					if (value instanceof Integer) {
    						// int value = ((Integer) value).intValue();
    						textValue = value.toString();
    					} else if (value instanceof String) {
    						// String s = (String) value;
    						textValue = value.toString();
    					} else if (value instanceof Double) {
    						// double d = ((Double) value).doubleValue();
    						textValue = String.format("%.2f", value);
    					} else if (value instanceof Float) {
    						// float f = ((Float) value).floatValue();
    						textValue = value.toString();
    					} else if (value instanceof Long) {
    						// long l = ((Long) value).longValue();
    						textValue = value.toString();
    					} else if (value instanceof Boolean) {
    						// boolean b = ((Boolean) value).booleanValue();
    						textValue = value.toString();
    					} else if (value instanceof Date) {
    						Date date = (Date) value;
    						SimpleDateFormat sdf = new SimpleDateFormat(datetimePattern);
    						textValue = sdf.format(date);
    					} else if ((value instanceof BigDecimal)) {
    						textValue = value.toString();
    					} else {
    						if (value != null) {
    							continue;
    						}
    					}
    					
    					sb.append("<Cell><Data ss:Type=\"String\">");
    					
    					// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
    					if (StringUtils.isNotBlank(textValue)) {
    						
    						Pattern p = Pattern.compile("^//d+(//.//d+)?$");
    						Matcher matcher = p.matcher(textValue);
    						if (matcher.matches()) {
    							// 是数字当作double处理
    							sb.append(Double.parseDouble(textValue));
    						} else {
    							sb.append(textValue);
    						}
    						
    					}
    					
    					sb.append("</Data></Cell>");
    					
    				}
    				
    				sb.append("</Row>");
    				sb.append("\n");
    				
    			}
    			
    			sb.append("</Table>");
    			sb.append("<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
    			sb.append("\n");
    			sb.append("<ProtectObjects>False</ProtectObjects>");
    			sb.append("\n");
    			sb.append("<ProtectScenarios>False</ProtectScenarios>");
    			sb.append("\n");
    			sb.append("</WorksheetOptions>");
    			sb.append("\n");
    			sb.append("</Worksheet>");
    			sb.append("</Workbook>");
    			sb.append("\n");
    			
    		} catch (SecurityException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} catch (InvocationTargetException e) {
    			e.printStackTrace();
    		}
    		
    		try {
    			outputStream.write(sb.toString().getBytes());
    			outputStream.flush();
    			outputStream.close();
    			sb = null;
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				outputStream.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    
    	
    
    }
    

      

     

    使用方式:

    @RequestMapping("/exportMsCard")
    	public void exportMsCard(HttpServletRequest req, HttpServletResponse res, 
    			Integer pageIndex, Integer pageSize, 
    			String cardNo, String mobile, String cinemaBaseName, Date startDate, Date endDate) {
    		try {
    			if(endDate != null){
    				endDate = DateUtils.dateAdd(endDate, 1, false);
    			}
    			List<MsCard> msCards = msCardService.list(pageIndex, pageSize, 
    					cardNo, mobile, cinemaBaseName, startDate, endDate);
    			
    			String[] headers = { "会员卡号", "会员昵称", "手机号码", "影院名称", "创建时间"};
    			String[] includeFieldNames = { "cardNo", "nickname", "mobile", "cinemaBaseName", "createTime"};
    			// 设置文件后缀并编码
    			String fileName = new String("运营平台-会员卡包-会员卡列表.xls".getBytes("UTF-8"), "iso8859-1");
    			// 设置响应的编码方式;
    			res.setCharacterEncoding("gb2312");
    			res.setHeader("Content-disposition", "attachment; filename=" + fileName);
    			res.setContentType("application/msexcel;charset=UTF-8");
    			// 导出订单Excel
    			ExportUtil exportUtil = new ExportUtil();
    			exportUtil.exportExcel("sheet", "", msCards, headers, includeFieldNames, new Integer[]{200}, res.getOutputStream(), null);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    

      

     注意:不能直接通过Ajax请求,需要通过表单提交。

     

    xml方式转Excel用到的属性:



     

    补充一个:

    ss:MergeAcross 表示跨列合并,如下:

    // 输出第一行的标题
    if(!StrUtils.isBlank(firstRowTitle)){
    	//ss:StyleID可以加row或者Cell,加在Row,整行(包括空的Cell)都有,加上Cell,只有Cell才有。
    	sb.append("<Row  ss:Height=\"30\">");
    	sb.append("<Cell ss:StyleID=\"header\" ss:MergeAcross=\""+ (headersLength - 1)+"\"><Data ss:Type=\"String\">" + firstRowTitle + "</Data></Cell>");
    	sb.append("</Row>");
    }
    

      

     注意是否需要减1,因为表示是跨多少列,那就是合并其它的几列,不包括自己,所以需要减 1

     

    万能方法:

    如果突然需要增加某些未知的属性,可以自己先创建一个Excel文件,做一个模板出来,然后另存为Xml文件,注意是Xml文件,保存后打开Xml文件查看自己创建的模板的某些属性应该怎么设置。但打开的xml文件比较乱,所以通过搜索找到自己对应的那个格子。

     

    源码下载见:http://fanshuyao.iteye.com/blog/2393131

     

    =============================

    ©Copyright 蕃薯耀 2017年9月13日

    http://www.cnblogs.com/fanshuyao/

    展开全文
  • java导出Excel工具类

    千次阅读 2015-03-25 10:30:33
    springmvc通过excel工具类实现的excel导出功能。

    废话不多说,直接上示例和代码,本人mvc框架使用的springmvc。

    控制器中方法如下:

    @RequestMapping("/getSystemExcel")
    public String getSystemExcel(String orgCode, HttpServletResponse response) {
    List<JdSystem> jdSystemsList = jdSystemService.queryJdSystemListByALL();
    String fileName = "系统列表";
    String[] colNames = { "系统编号", "系统名称", "系统简称", "访问地址", "系统接口人",
    "创建时间", "修改时间", "启用状态" };
    LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
    map.put("系统编号", "System_id");
    map.put("系统名称", "System_name");
    map.put("系统简称", "System_Ename");
    map.put("访问地址", "siteUrl");
    map.put("系统接口人", "erp");
    map.put("创建时间", "created");
    map.put("修改时间", "modified");
    map.put("启用状态", "yn");
    String search = "无";
    try {
    ExcelUtil.downloadExcel(fileName, colNames, map, search,
    jdSystemsList, response);
    } catch (Exception e) {
    logger.error(e.getMessage(), e);
    }
    return null;
    }
    

    excel工具类如下:

    package com.jd.heads.common.utils;
    
    
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map.Entry;
    import java.util.Set;
    
    
    import javax.servlet.http.HttpServletResponse;
    
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    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.CellRangeAddress;
    import org.apache.poi.ss.usermodel.CellStyle;
    import org.apache.poi.ss.usermodel.Font;
    import org.apache.poi.ss.usermodel.IndexedColors;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    
    /**
     * 根据传入的list数据创建excel文件并下载
     *
     * @ClassName: ExcelUtil
     * @author caozhifei
     * @date 2015-3-25 上午10:21:51
     *
     */
    @SuppressWarnings("deprecation")
    public class ExcelUtil {
    private static Logger log = LoggerFactory.getLogger(ExcelUtil.class);
    private static CellStyle titleStyle; // 标题行样式
    private static Font titleFont; // 标题行字体
    private static CellStyle dateStyle; // 条件行样式
    private static Font dateFont; // 日期行字体
    private static CellStyle headStyle; // 表头行样式
    private static Font headFont; // 表头行字体
    private static CellStyle contentStyle; // 内容行样式
    private static Font contentFont; // 内容行字体
    /**
    * 根据数据集合生成excel文件并下载
    *  @Method_Name    : downloadExcel
    *  @param fileName excel文件名称,工作簿和生成的内容标题都用这个名称
    *  @param colNames 需要导出的excel列名数组,为null时导出map中所有的key
    *  @param map 列名与集合中实体类属性的对应关系
    *  @param searchParam 查询条件参数 
    *  @param list 需要导出的数据集合
    *  @param response
    *  @throws Exception 
    *  @return         : void
    *  @Creation Date  : 2014年5月6日 上午11:38:03
    *  @version        : v1.00
    * @Author         : caozhifei 
    *  @Update Date    : 2014年5月6日 上午13:55:03
    *  @Update Author  : caozhifei log 为null时导出map中所有的key
    */
    public static void downloadExcel(String fileName, String[] colNames,
    LinkedHashMap<String, String> map, String searchParam, List<?> list,
    HttpServletResponse response) throws Exception {
    
    String[] colContents = null;
    if(colNames==null){
    colNames = (String[]) map.keySet().toArray(new String[map.keySet().size()]);
    colContents = (String[]) map.values().toArray(new String[map.values().size()]);
    }else{
    colContents = new String[colNames.length];
    for (int i = 0; i < colNames.length; i++) {
    colContents[i] = map.get(colNames[i]);
    }
    }
    log.debug("excel colNames is "+java.util.Arrays.toString(colNames));
    
    log.debug("excel colContents is "+java.util.Arrays.toString(colContents));
    byte[] in = ExcelUtil.createExcel(fileName, colNames, colContents,
    searchParam, list);
    // 进行转码,使其支持中文文件名
    String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
    response.setHeader("content-disposition", "attachment;filename="
    + codedFileName + ".xls");
    BufferedOutputStream bos = new BufferedOutputStream(
    response.getOutputStream());
    bos.write(in);
    bos.flush();
    bos.close();
    log.debug("download excel success,the excel file name is "+fileName);
    }
    
    
    
    /**
    * 根据集合数据创建excel文件流
    *  @Method_Name    : createExcel
    *  @param fileName 文件名称
    *  @param colNames 列名数组
    *  @param colContents 对应的数据属性数组
    *  @param searchParam 查询条件
    *  @param list 需要导出的数据集合
    *  @return
    *  @throws Exception 
    *  @version        : v1.00
    *  @Author         : caozhifei 
    *  @Update Date    : 
    *  @Update Author  :
    */
    private static byte[] createExcel(String fileName, String[] colNames,
    String[] colContents, String searchParam, List<?> list)
    throws Exception {
    HSSFWorkbook wb = null;
    wb = init(wb);
    
    LinkedHashMap<String, List<?>> map = new LinkedHashMap<String, List<?>>();
    // map.put("账户组访问网站", dataList);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    List<String[]> headNames = new ArrayList<String[]>();
    // 设置Excel文件的列名称
    // 设置工作薄名称
    map.put(fileName, list);
    headNames.add(colNames);
    List<String[]> fieldNames = new ArrayList<String[]>();
    // 设置列内容
    fieldNames.add(colContents);
    ExportSetInfo setInfo = new ExportSetInfo();
    setInfo.setObjsMap(map);
    setInfo.setFieldNames(fieldNames);
    // 设置Excel内容的标题
    setInfo.setTitles(new String[] { fileName });
    // 设置显示的查询条件
    setInfo.setSearch(new String[] { searchParam });
    setInfo.setHeadNames(headNames);
    setInfo.setOut(baos);
    // 将需要导出的数据输出到baos
    ExcelUtil.export2Excel(setInfo, wb);
    return baos.toByteArray();
    }
    
    
    /**
    * @throws IllegalAccessException
    * @throws IllegalArgumentException
    * @Description: 将Map里的集合对象数据输出Excel数据流
    */
    private static void export2Excel(ExportSetInfo setInfo, HSSFWorkbook wb)
    throws IOException, IllegalArgumentException,
    IllegalAccessException {
    wb = init(wb);
    Set<Entry<String, List<?>>> set = setInfo.getObjsMap().entrySet();
    String[] sheetNames = new String[setInfo.getObjsMap().size()];
    int sheetNameNum = 0;
    for (Entry<String, List<?>> entry : set) {
    sheetNames[sheetNameNum] = entry.getKey();
    sheetNameNum++;
    }
    HSSFSheet[] sheets = getSheets(setInfo.getObjsMap().size(), sheetNames,
    wb);
    int sheetNum = 0;
    for (Entry<String, List<?>> entry : set) {
    // Sheet
    List<?> objs = entry.getValue();
    // 标题行
    createTableTitleRow(setInfo, sheets, sheetNum);
    // 日期行
    createTableDateRow(setInfo, sheets, sheetNum);
    // 表头
    creatTableHeadRow(setInfo, sheets, sheetNum);
    // 表体
    String[] fieldNames = setInfo.getFieldNames().get(sheetNum);
    int rowNum = 3;
    for (Object obj : objs) {
    HSSFRow contentRow = sheets[sheetNum].createRow(rowNum);
    contentRow.setHeight((short) 300);
    HSSFCell[] cells = getCells(contentRow, setInfo.getFieldNames()
    .get(sheetNum).length);
    int cellNum = 1; // 去掉一列序号,因此从1开始
    if (fieldNames != null) {
    for (int num = 0; num < fieldNames.length; num++) {
    Object value = ReflectionUtil.invokeGetterMethod(obj,
    fieldNames[num]);
    cells[cellNum].setCellValue(value == null ? "" : value
    .toString());
    cellNum++;
    }
    }
    rowNum++;
    }
    // adjustColumnSize(sheets, sheetNum, fieldNames); // 自动调整列宽
    sheetNum++;
    }
    wb.write(setInfo.getOut());
    }
    
    
    /**
    * 初始化HSSFWorkbook
    *  @Method_Name    : init
    *  @param wb
    *  @return 
    *  @return         : HSSFWorkbook
    *  @Creation Date  : 2014年5月6日 上午11:46:00
    *  @version        : v1.00
    *  @Author         : caozhifei 
    *  @Update Date    : 
    *  @Update Author  :
    */
    private static HSSFWorkbook init(HSSFWorkbook wb) {
    wb = new HSSFWorkbook();
    
    
    titleFont = wb.createFont();
    titleStyle = wb.createCellStyle();
    dateStyle = wb.createCellStyle();
    dateFont = wb.createFont();
    headStyle = wb.createCellStyle();
    headFont = wb.createFont();
    contentStyle = wb.createCellStyle();
    contentFont = wb.createFont();
    
    
    initTitleCellStyle();
    initTitleFont();
    initDateCellStyle();
    initDateFont();
    initHeadCellStyle();
    initHeadFont();
    initContentCellStyle();
    initContentFont();
    return wb;
    }
    
    
    /**
    * @Description: 自动调整列宽
    */
    @SuppressWarnings("unused")
    private static void adjustColumnSize(HSSFSheet[] sheets, int sheetNum,
    String[] fieldNames) {
    for (int i = 0; i < fieldNames.length + 1; i++) {
    sheets[sheetNum].autoSizeColumn(i, true);
    }
    }
    
    
    /**
    * @Description: 创建标题行(需合并单元格)
    */
    private static void createTableTitleRow(ExportSetInfo setInfo,
    HSSFSheet[] sheets, int sheetNum) {
    CellRangeAddress titleRange = new CellRangeAddress(0, 0, 0, setInfo
    .getFieldNames().get(sheetNum).length);
    sheets[sheetNum].addMergedRegion(titleRange);
    HSSFRow titleRow = sheets[sheetNum].createRow(0);
    titleRow.setHeight((short) 800);
    HSSFCell titleCell = titleRow.createCell(0);
    titleCell.setCellStyle(titleStyle);
    titleCell.setCellValue(setInfo.getTitles()[sheetNum]);
    }
    
    
    /**
    * @Description: 创建条件行(需合并单元格)
    */
    private static void createTableDateRow(ExportSetInfo setInfo,
    HSSFSheet[] sheets, int sheetNum) {
    CellRangeAddress dateRange = new CellRangeAddress(1, 1, 0, setInfo
    .getFieldNames().get(sheetNum).length);
    sheets[sheetNum].addMergedRegion(dateRange);
    HSSFRow dateRow = sheets[sheetNum].createRow(1);
    dateRow.setHeight((short) 350);
    HSSFCell dateCell = dateRow.createCell(0);
    dateCell.setCellStyle(dateStyle);
    dateCell.setCellValue(setInfo.getSearch()[sheetNum]);
    }
    
    
    /**
    * @Description: 创建表头行(需合并单元格)
    */
    private static void creatTableHeadRow(ExportSetInfo setInfo,
    HSSFSheet[] sheets, int sheetNum) {
    // 表头
    HSSFRow headRow = sheets[sheetNum].createRow(2);
    headRow.setHeight((short) 350);
    // 序号列
    HSSFCell snCell = headRow.createCell(0);
    snCell.setCellStyle(headStyle);
    snCell.setCellValue("序号");
    // 列头名称
    for (int num = 1, len = setInfo.getHeadNames().get(sheetNum).length; num <= len; num++) {
    HSSFCell headCell = headRow.createCell(num);
    headCell.setCellStyle(headStyle);
    headCell.setCellValue(setInfo.getHeadNames().get(sheetNum)[num - 1]);
    }
    }
    
    
    /**
    * @Description: 创建所有的Sheet
    */
    private static HSSFSheet[] getSheets(int num, String[] names,
    HSSFWorkbook wb) {
    HSSFSheet[] sheets = new HSSFSheet[num];
    for (int i = 0; i < num; i++) {
    sheets[i] = wb.createSheet(names[i]);
    }
    return sheets;
    }
    
    
    /**
    * @Description: 创建内容行的每一列(附加一列序号)
    */
    private static HSSFCell[] getCells(HSSFRow contentRow, int num) {
    HSSFCell[] cells = new HSSFCell[num + 1];
    
    
    for (int i = 0, len = cells.length; i < len; i++) {
    cells[i] = contentRow.createCell(i);
    cells[i].setCellStyle(contentStyle);
    }
    // 设置序号列值,因为出去标题行和日期行,所有-2
    cells[0].setCellValue(contentRow.getRowNum() - 2);
    
    
    return cells;
    }
    
    
    /**
    * @Description: 初始化标题行样式
    */
    private static void initTitleCellStyle() {
    titleStyle.setAlignment(CellStyle.ALIGN_CENTER);
    titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    titleStyle.setFont(titleFont);
    titleStyle.setFillBackgroundColor(IndexedColors.SKY_BLUE.getIndex());
    }
    
    
    /**
    * @Description: 初始化日期行样式
    */
    private static void initDateCellStyle() {
    dateStyle.setAlignment(CellStyle.ALIGN_LEFT);
    dateStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    dateStyle.setFont(dateFont);
    dateStyle.setFillBackgroundColor(IndexedColors.SKY_BLUE.getIndex());
    }
    
    
    /**
    * @Description: 初始化表头行样式
    */
    private static void initHeadCellStyle() {
    headStyle.setAlignment(CellStyle.ALIGN_CENTER);
    headStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    headStyle.setFont(headFont);
    headStyle.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
    headStyle.setBorderTop(CellStyle.BORDER_MEDIUM);
    headStyle.setBorderBottom(CellStyle.BORDER_THIN);
    headStyle.setBorderLeft(CellStyle.BORDER_THIN);
    headStyle.setBorderRight(CellStyle.BORDER_THIN);
    headStyle.setTopBorderColor(IndexedColors.BLUE.getIndex());
    headStyle.setBottomBorderColor(IndexedColors.BLUE.getIndex());
    headStyle.setLeftBorderColor(IndexedColors.BLUE.getIndex());
    headStyle.setRightBorderColor(IndexedColors.BLUE.getIndex());
    }
    
    
    /**
    * @Description: 初始化内容行样式
    */
    private static void initContentCellStyle() {
    contentStyle.setAlignment(CellStyle.ALIGN_CENTER);
    contentStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    contentStyle.setFont(contentFont);
    contentStyle.setBorderTop(CellStyle.BORDER_THIN);
    contentStyle.setBorderBottom(CellStyle.BORDER_THIN);
    contentStyle.setBorderLeft(CellStyle.BORDER_THIN);
    contentStyle.setBorderRight(CellStyle.BORDER_THIN);
    contentStyle.setTopBorderColor(IndexedColors.BLUE.getIndex());
    contentStyle.setBottomBorderColor(IndexedColors.BLUE.getIndex());
    contentStyle.setLeftBorderColor(IndexedColors.BLUE.getIndex());
    contentStyle.setRightBorderColor(IndexedColors.BLUE.getIndex());
    contentStyle.setWrapText(true); // 字段换行
    }
    
    
    /**
    * @Description: 初始化标题行字体
    */
    private static void initTitleFont() {
    titleFont.setFontName("华文楷体");
    titleFont.setFontHeightInPoints((short) 20);
    titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    titleFont.setCharSet(Font.DEFAULT_CHARSET);
    titleFont.setColor(IndexedColors.BLUE_GREY.getIndex());
    }
    
    
    /**
    * @Description: 初始化条件行字体
    */
    private static void initDateFont() {
    dateFont.setFontName("隶书");
    dateFont.setFontHeightInPoints((short) 10);
    dateFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    dateFont.setCharSet(Font.DEFAULT_CHARSET);
    dateFont.setColor(IndexedColors.BLUE_GREY.getIndex());
    }
    
    
    /**
    * @Description: 初始化表头行字体
    */
    private static void initHeadFont() {
    headFont.setFontName("宋体");
    headFont.setFontHeightInPoints((short) 10);
    headFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    headFont.setCharSet(Font.DEFAULT_CHARSET);
    headFont.setColor(IndexedColors.BLUE_GREY.getIndex());
    }
    
    
    /**
    * @Description: 初始化内容行字体
    */
    private static void initContentFont() {
    contentFont.setFontName("宋体");
    contentFont.setFontHeightInPoints((short) 10);
    contentFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
    contentFont.setCharSet(Font.DEFAULT_CHARSET);
    contentFont.setColor(IndexedColors.BLUE_GREY.getIndex());
    }
    
    
    /**
    * @Description: 封装Excel导出的设置信息
    * @author: 曹志飞
    */
    public static class ExportSetInfo {
    private LinkedHashMap<String, List<?>> objsMap;
    
    
    private String[] titles;
    
    
    private String[] search;
    
    
    private List<String[]> headNames;
    
    
    private List<String[]> fieldNames;
    
    
    private OutputStream out;
    
    
    public LinkedHashMap<String, List<?>> getObjsMap() {
    return objsMap;
    }
    
    
    /**
    * @param objMap
    *            导出数据
    * 
    *            泛型 String : 代表sheet名称 List : 代表单个sheet里的所有行数据
    */
    public void setObjsMap(LinkedHashMap<String, List<?>> objsMap) {
    this.objsMap = objsMap;
    }
    
    
    public List<String[]> getFieldNames() {
    return fieldNames;
    }
    
    
    public String[] getSearch() {
    return search;
    }
    
    
    public void setSearch(String[] search) {
    this.search = search;
    }
    
    
    /**
    * @param clazz
    *            对应每个sheet里的每行数据的对象的属性名称
    */
    public void setFieldNames(List<String[]> fieldNames) {
    this.fieldNames = fieldNames;
    }
    
    
    public String[] getTitles() {
    return titles;
    }
    
    
    /**
    * @param titles
    *            对应每个sheet里的标题,即顶部大字
    */
    public void setTitles(String[] titles) {
    this.titles = titles;
    }
    
    
    public List<String[]> getHeadNames() {
    return headNames;
    }
    
    
    /**
    * @param headNames
    *            对应每个页签的表头的每一列的名称
    */
    public void setHeadNames(List<String[]> headNames) {
    this.headNames = headNames;
    }
    
    
    public OutputStream getOut() {
    return out;
    }
    
    
    /**
    * @param out
    *            Excel数据将输出到该输出流
    */
    public void setOut(OutputStream out) {
    this.out = out;
    }
    }
    }
    


    反射工具类如下:

    package com.jd.heads.common.utils;
    
    
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Date;
    import java.util.List;
    
    
    import org.apache.commons.beanutils.BeanUtils;
    import org.apache.commons.beanutils.ConvertUtils;
    import org.apache.commons.beanutils.PropertyUtils;
    import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
    import org.apache.commons.lang.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.Assert;
    
    
    /**
     * 反射工具类 提供访问私有变量,获取泛型类型Class, 提取集合中元素的属性, 转换字符串到对象等Util函数.
     * 
     * 
     * 
     * @ClassName : ReflectionUtil
     * @Author : caozhifei
     * 
     */
    public class ReflectionUtil {
    private static Logger logger = LoggerFactory
    .getLogger(ReflectionUtil.class);
    
    
    static {
    DateLocaleConverter dc = new DateLocaleConverter();
    // dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
    ConvertUtils.register(dc, Date.class);
    }
    
    
    /**
    * 调用Getter方法.
    */
    public static Object invokeGetterMethod(Object target, String propertyName) {
    String getterMethodName = "get" + StringUtils.capitalize(propertyName);
    return invokeMethod(target, getterMethodName, new Class[] {},
    new Object[] {});
    }
    
    
    /**
    * 调用Setter方法.使用value的Class来查找Setter方法.
    */
    public static void invokeSetterMethod(Object target, String propertyName,
    Object value) {
    invokeSetterMethod(target, propertyName, value, null);
    }
    
    
    /**
    * 调用Setter方法.
    * 
    * @param propertyType
    *            用于查找Setter方法,为空时使用value的Class替代.
    */
    public static void invokeSetterMethod(Object target, String propertyName,
    Object value, Class<?> propertyType) {
    Class<?> type = propertyType != null ? propertyType : value.getClass();
    String setterMethodName = "set" + StringUtils.capitalize(propertyName);
    invokeMethod(target, setterMethodName, new Class[] { type },
    new Object[] { value });
    }
    
    
    /**
    * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
    */
    public static Object getFieldValue(final Object object,
    final String fieldName) {
    Field field = getDeclaredField(object, fieldName);
    
    
    if (field == null) {
    throw new IllegalArgumentException("Could not find field ["
    + fieldName + "] on target [" + object + "]");
    }
    
    
    makeAccessible(field);
    
    
    Object result = null;
    try {
    result = field.get(object);
    } catch (IllegalAccessException e) {
    logger.error("不可能抛出的异常{}" + e.getMessage(), e);
    }
    return result;
    }
    
    
    /**
    * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
    */
    public static void setFieldValue(final Object object,
    final String fieldName, final Object value) {
    Field field = getDeclaredField(object, fieldName);
    
    
    if (field == null) {
    throw new IllegalArgumentException("Could not find field ["
    + fieldName + "] on target [" + object + "]");
    }
    
    
    makeAccessible(field);
    
    
    try {
    field.set(object, value);
    } catch (IllegalAccessException e) {
    logger.error("不可能抛出的异常:{}" + e.getMessage(), e);
    }
    }
    
    
    /**
    * 直接调用对象方法, 无视private/protected修饰符.
    */
    public static Object invokeMethod(final Object object,
    final String methodName, final Class<?>[] parameterTypes,
    final Object[] parameters) {
    Method method = getDeclaredMethod(object, methodName, parameterTypes);
    if (method == null) {
    throw new IllegalArgumentException("Could not find method ["
    + methodName + "] parameterType " + parameterTypes
    + " on target [" + object + "]");
    }
    
    
    method.setAccessible(true);
    
    
    try {
    return method.invoke(object, parameters);
    } catch (Exception e) {
    throw convertReflectionExceptionToUnchecked(e);
    }
    }
    
    
    /**
    * 循环向上转型, 获取对象的DeclaredField.
    * 
    * 如向上转型到Object仍无法找到, 返回null.
    */
    protected static Field getDeclaredField(final Object object,
    final String fieldName) {
    Assert.notNull(object, "object不能为空");
    Assert.hasText(fieldName, "fieldName");
    for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
    .getSuperclass()) {
    try {
    return superClass.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {// NOSONAR
    // Field不在当前类定义,继续向上转型
    logger.error(e.getMessage(), e);
    }
    }
    return null;
    }
    
    
    /**
    * 强行设置Field可访问.
    */
    protected static void makeAccessible(final Field field) {
    if (!Modifier.isPublic(field.getModifiers())
    || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
    field.setAccessible(true);
    }
    }
    
    
    /**
    * 循环向上转型, 获取对象的DeclaredMethod.
    * 
    * 如向上转型到Object仍无法找到, 返回null.
    */
    protected static Method getDeclaredMethod(Object object, String methodName,
    Class<?>[] parameterTypes) {
    Assert.notNull(object, "object不能为空");
    
    
    for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
    .getSuperclass()) {
    try {
    return superClass.getDeclaredMethod(methodName, parameterTypes);
    } catch (NoSuchMethodException e) {// NOSONAR
    // Method不在当前类定义,继续向上转型
    logger.error(e.getMessage(), e);
    }
    }
    return null;
    }
    
    
    /**
    * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. eg. public UserDao
    * extends HibernateDao<User>
    * 
    * @param clazz
    *            The class to introspect
    * @return the first generic declaration, or Object.class if cannot be
    *         determined
    */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
    return getSuperClassGenricType(clazz, 0);
    }
    
    
    /**
    * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
    * 
    * 如public UserDao extends HibernateDao<User,Long>
    * 
    * @param clazz
    *            clazz The class to introspect
    * @param index
    *            the Index of the generic ddeclaration,start from 0.
    * @return the index generic declaration, or Object.class if cannot be
    *         determined
    */
    @SuppressWarnings("unchecked")
    public static Class getSuperClassGenricType(final Class clazz,
    final int index) {
    Type genType = clazz.getGenericSuperclass();
    
    
    if (!(genType instanceof ParameterizedType)) {
    logger.warn(clazz.getSimpleName()
    + "'s superclass not ParameterizedType");
    return Object.class;
    }
    
    
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    
    
    if (index >= params.length || index < 0) {
    logger.warn("Index: " + index + ", Size of "
    + clazz.getSimpleName() + "'s Parameterized Type: "
    + params.length);
    return Object.class;
    }
    if (!(params[index] instanceof Class)) {
    logger.warn(clazz.getSimpleName()
    + " not set the actual class on superclass generic parameter");
    return Object.class;
    }
    
    
    return (Class) params[index];
    }
    
    
    /**
    * 提取集合中的对象的属性(通过getter函数), 组合成List.
    * 
    * @param collection
    *            来源集合.
    * @param propertyName
    *            要提取的属性名.
    */
    @SuppressWarnings("unchecked")
    public static List convertElementPropertyToList(
    final Collection collection, final String propertyName) {
    List list = new ArrayList();
    
    
    try {
    for (Object obj : collection) {
    list.add(PropertyUtils.getProperty(obj, propertyName));
    }
    } catch (Exception e) {
    throw convertReflectionExceptionToUnchecked(e);
    }
    
    
    return list;
    }
    
    
    /**
    * 提取集合中的对象的属性(通过getter函数), 组合成由分割符分隔的字符串.
    * 
    * @param collection
    *            来源集合.
    * @param propertyName
    *            要提取的属性名.
    * @param separator
    *            分隔符.
    */
    @SuppressWarnings("unchecked")
    public static String convertElementPropertyToString(
    final Collection collection, final String propertyName,
    final String separator) {
    List list = convertElementPropertyToList(collection, propertyName);
    return StringUtils.join(list, separator);
    }
    
    
    /**
    * 转换字符串到相应类型.
    * 
    * @param value
    *            待转换的字符串
    * @param toType
    *            转换目标类型
    */
    @SuppressWarnings("unchecked")
    public static <T> T convertStringToObject(String value, Class<T> toType) {
    try {
    return (T) ConvertUtils.convert(value, toType);
    } catch (Exception e) {
    throw convertReflectionExceptionToUnchecked(e);
    }
    }
    
    
    /**
    * 将反射时的checked exception转换为unchecked exception.
    */
    public static RuntimeException convertReflectionExceptionToUnchecked(
    Exception e) {
    return convertReflectionExceptionToUnchecked(null, e);
    }
    
    
    public static RuntimeException convertReflectionExceptionToUnchecked(
    String desc, Exception e) {
    desc = (desc == null) ? "Unexpected Checked Exception." : desc;
    if (e instanceof IllegalAccessException
    || e instanceof IllegalArgumentException
    || e instanceof NoSuchMethodException) {
    return new IllegalArgumentException(desc, e);
    } else if (e instanceof InvocationTargetException) {
    return new RuntimeException(desc,
    ((InvocationTargetException) e).getTargetException());
    } else if (e instanceof RuntimeException) {
    return (RuntimeException) e;
    }
    return new RuntimeException(desc, e);
    }
    
    
    public static final <T> T getNewInstance(Class<T> cls) {
    try {
    return cls.newInstance();
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    }
    return null;
    }
    
    
    /**
    * 拷贝 source 指定的porperties 属性 到 dest中
    * 
    * @return void
    * @throws InvocationTargetException
    * @throws IllegalAccessException
    */
    public static void copyPorperties(Object dest, Object source,
    String[] porperties) throws InvocationTargetException,
    IllegalAccessException {
    for (String por : porperties) {
    Object srcObj = invokeGetterMethod(source, por);
    logger.debug("属性名:" + por + "------------- 属性值:" + srcObj);
    if (srcObj != null) {
    try {
    BeanUtils.setProperty(dest, por, srcObj);
    } catch (IllegalArgumentException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    throw e;
    } catch (InvocationTargetException e) {
    throw e;
    }
    }
    }
    }
    
    
    /**
    * 两者属性名一致时,拷贝source里的属性到dest里
    * 
    * @return void
    * @throws IllegalAccessException
    * @throws InvocationTargetException
    */
    @SuppressWarnings("unchecked")
    public static void copyPorperties(Object dest, Object source)
    throws IllegalAccessException, InvocationTargetException {
    Class srcCla = source.getClass();
    Field[] fsF = srcCla.getDeclaredFields();
    
    
    for (Field s : fsF) {
    String name = s.getName();
    Object srcObj = invokeGetterMethod(source, name);
    try {
    BeanUtils.setProperty(dest, name, srcObj);
    } catch (IllegalArgumentException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    throw e;
    } catch (InvocationTargetException e) {
    throw e;
    }
    }
    }
    
    
    }


    需要依赖的jar包如下

    <!-- excel poi -->
    <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.8</version>
    </dependency>
    <dependency>
    <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.8.3</version>
    </dependency>


    展开全文
  • java导出excel工具类 以及jar包很简单 里面注释很全的 大家可以下载看看
  • NULL 博文链接:https://fanshuyao.iteye.com/blog/2393131
  • Java导出Excel工具类

    2014-01-09 23:13:49
    工具类 import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache

    所需jar包 poi

    工具类

    import java.io.IOException;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    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;
    
    public class ExcelTool {
    	/**
    	 * *
    	 * 
    	 * @param filename 保存到客户端的文件名			例:用户.xls
    	 * @param title 标题行						 例:String[]{"名称","地址"}
    	 * @param key 从查询结果List取得的MAP的KEY顺序,
    	 * 				需要和title顺序匹配,				例:String[]{"name","address"}
    	 * @param values  结果集
    	 * @param httpServletResponse
    	 * @throws IOException
    	 */
    	public static void createN(String filename, String[] title, String[] key, List<Map> values, HttpServletResponse httpServletResponse) throws IOException {
    		String filename2 = new String(filename.getBytes(), "iso-8859-1");
    		ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
    		HSSFWorkbook workbook = null;
    		httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + filename2);
    		httpServletResponse.setContentType("application/x-download");
    		workbook = new HSSFWorkbook();
    		HSSFSheet sheet = workbook.createSheet();
    		HSSFRow row = null;
    		HSSFCell cell = null;
    		row = sheet.createRow((short) 0);
    		for (int i = 0; title != null && i < title.length; i++) {
    			cell = row.createCell((short) i);
    			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    			cell.setCellValue(new HSSFRichTextString(title[i]));
    		}
    		Map map = null;
    		for (int i = 0; values != null && i < values.size(); i++) {
    			row = sheet.createRow((short) (i + 1));
    			map = values.get(i);
    			for (int i2 = 0; i2 < key.length; i2++) {
    				cell = row.createCell((short) (i2));
    				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    				if (map.get(key[i2]) == null) {
    					cell.setCellValue(new HSSFRichTextString(""));
    				} else {
    					cell.setCellValue(new HSSFRichTextString(map.get(key[i2]).toString()));
    				}
    			}
    		}
    		workbook.write(servletOutputStream);
    		servletOutputStream.flush();
    		servletOutputStream.close();
    	}
    }

    应用实例(spring mvc)

    在Controller中

    @ResponseBody
    	@RequestMapping(value = "excel")
    	public void excel(HttpServletRequest request, HttpServletResponse response) {
    		String filename = "用户列表.xls";
    		List<User> list = userService.getList(null, null);
    		String[] title = { "用户名", "条形码", "创建时间" };
    		String[] key = { "userPhoneCode", "userBarCode", "createTime" };
    		Map<String, String> map;
    		@SuppressWarnings("rawtypes")
    		List<Map> values = new LinkedList<Map>();
    		for (User user : list) {
    			map = new TreeMap<String, String>();
    			map.put("userPhoneCode", user.getUserPhoneCode());
    			map.put("userBarCode", user.getUserBarCode());
    			map.put("createTime", user.getCreateTime());
    			values.add(map);
    		}
    		try {
    			ExcelTool.createN(filename, title, key, values, response);
    		} catch (IOException e) {
    		}
    	}


    展开全文
  • java表数据导出excel工具类,以及支持的jar包,解压添加jar包到工程即可使用
  • 文章目录项目环境:实现功能:工具类实现定义参数bean:ExportExcelBean.java定义导出excel的表格主题:ExportExcelTheme.java【重点】导出excel工具类:ExportExcelUtil.java测试导出excel编写测试controller:...
  • java导出excel工具类(贼好用)

    千次阅读 2019-07-11 18:22:57
    项目中自用的导出excel工具: 实体: package com.mapuni.survey.entity; public class ExcelEntity { private String field; private String title; public String getField() { return field; } ...
  • * 导出excel(利用反射机制) * String[] title = {"订单号","商品名称","商品价格","创建时间"}; * String[] field = {"orderNum","productName","productPrice","createTime"}; * ExportTools.export("sellJoin...
  • 主要介绍了java实现的导出Excel工具类,结合具体实例形式分析了java导出Excel导出并生成Excel表格相关操作技巧与注意事项,需要的朋友可以参考下
  • Java导出Excel工具类及其Demo
  • 一个实用的java导入导出Excel工具类,基于开源的Java Excel API(JXL)纯java类库实现,Windows和Linux系统下均可使用。 主要实现功能如下: 导出:将List转化为Excel(listToExcel)。 导入:将Excel转化为List...
  • java使用POI导出 Excel+图片工具类 ,里面含有poi jar包,只调用接口即可直接保存Excel。使用的时候需先把数据封装,具体包装需根据实际导出数据进行处理。文件demo中只提供包装格式。
  • JAVA导出Excel工具类

    千次阅读 2019-09-20 17:37:39
    JAVA导出Excel工具类 /** *标记的步骤一到十二是主要要用的方法,我是将自己写需求时的代码直接复制过来的,所以当中会穿插 *一些我自己的需求方面的代码,做此博文,是方便以后自己用 * * */ import ...
  • java导出excel文档通用工具类

    热门讨论 2012-05-08 23:21:35
    java导出excel文档通用工具类,使用方便。 可选择性的生成报表表头。
  • 使用POI对excel文件操作的工具类,代码注释最全,欢迎使用,谢谢
  • java导出封装成工具类
  • 主要介绍了Java使用excel工具类导出对象功能,结合实例形式分析了java创建及导出Excel数据的具体步骤与相关操作技巧,需要的朋友可以参考下
  • java的poi的导入工具类,只需要传入两个arrayList,一个是execl的标题,一个是ececl的数据,就可以直接导出到execl里面,支持最新的execl,全新封装的,让每一个人都会使用poi导出execl!
  • 工具类实现java导出树形结构的方法,并未采用excel分组功能实现,而是根据树节点显示层级设置excel样式。针对easyUi,treeGrid开发的导出excel功能。方法简便实用、性强、通俗易懂。项目中亲测,no problem。
  • 自己写的导出excel报表的公共方法,该公共方法主要用于非横向流动性报表导出 ExcelUtil.java 1.创立excel基本初始步骤 XSSFWorkbook wb = new XSSFWorkbook(); XSSFCellStyle cellStyle = excelUtil....
  • java Excel工具类,导入导出Excel数据,导入数据对合并表格有判断获取数据,导出数据到Excel,Excel文件不存在会创建。 博客:https://blog.csdn.net/qq_37902949/article/details/81230640

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 15,272
精华内容 6,108
关键字:

java导出excel工具类

java 订阅