【java】反射+poi 导出excel

反射 导出的数组转变成对象

private static  Object expexcelMaptobean(Class<?> cobj,Map<String,String> map,int[] expColums,String[] params) throws InstantiationException, IllegalAccessException{
		Object t=cobj.newInstance();
		Set<Entry<String, String>> set=map.entrySet();
		int i=0;
		for(Entry<String, String> s:set){
			String field=s.getKey();
			field=field.substring(0,1).toUpperCase()+field.substring(1);
			try {
				Method m = null ;
				for(Class<?> clazz = cobj; clazz != Object.class ; clazz = clazz.getSuperclass()) {

						Method[] mehhods= clazz.getDeclaredMethods();
						for(Method md:mehhods){
							if(("set"+field).equals(md.getName())){
								Type[] paramclass=md.getParameterTypes();
								for(Type paramType:paramclass){
									String paramval=params[expColums[i]]+"";
									m =clazz.getDeclaredMethod("set"+field,(Class[])paramclass) ;
									if(paramType.getTypeName().equals("java.math.BigDecimal") ){
										boolean isNum = paramval.matches("\\d+(\\.\\d+)?");
										if(!isNum){
											m.invoke(t,new BigDecimal(0));
										}else{
											m.invoke(t,new BigDecimal(paramval));
										}
									}else{
										m.invoke(t,paramval);
									}
								}

							}
						}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(expColums[i]>params.length-1){
				break;
			}
			if(i==expColums.length-1 && (params.length>=expColums.length)){
				break;
			}
			i++;
		}
		return t;
	}

测试

public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		String[] params={"100","10000","ccc","dddd","eeee"};
		int[] expColums={1,2};
		Map<String,String> titleMap = new LinkedHashMap<String,String>();
		titleMap.put("ackAmt", "产品代码"); 
		titleMap.put("appno", "产品代码"); 
		Bean f=(Bean )expexcelMaptobean(Bean.class,titleMap,expColums,params);
		System.out.println(f.getAckAmt());
	}

导出excel 工具类


import java.io.File;
import java.io.FileOutputStream;
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.regex.Matcher;
import java.util.regex.Pattern;

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.ss.util.CellRangeAddress;

public final  class ExportExcel {
	public static  String saveExpExcelDir; //导出excel保存位置
	private ExportExcel() {

	}
	static{
		Map<String,String> map = System.getenv();
		saveExpExcelDir="C:\\Users"+File.separator+map.get("USERNAME")+File.separator+"Desktop"+File.separator+"ccjj";
	}

	/***
	 * 工作簿
	 */
	private static HSSFWorkbook workbook;

	/***
	 * sheet
	 */
	private static HSSFSheet sheet;
	/***
	 * 标题行开始位置
	 */
	private static final int TITLE_START_POSITION = 0;

	/***
	 * 时间行开始位置
	 */
	private static final int DATEHEAD_START_POSITION = 0;

	/***
	 * 表头行开始位置
	 */
	private static final int HEAD_START_POSITION = 0;

	/***
	 * 文本行开始位置
	 */
	private static final int CONTENT_START_POSITION = 1;

	/**
	 * 
	 * @param dataList
	 *        对象集合
	 * @param titleMap
	 *        表头信息(对象属性名称->要显示的标题值)[按顺序添加]
	 * @param sheetName
	 *        sheet名称和表头值
	 */
	public static void excelExport(List<?> dataList, Map<String, String> titleMap, String sheetName,String filepathandname) {
		initHSSFWorkbook(sheetName);// 初始化workbook
		//		createTitleRow(titleMap, sheetName);// 标题行
		//		createDateHeadRow(titleMap);// 时间行
		createHeadRow(titleMap);// 表头行
		createContentRow(dataList, titleMap);// 文本行
		//		autoSizeColumn(100);//设置自动伸缩
		try {
			OutputStream out = new FileOutputStream(filepathandname);
			workbook.write(out);
			out.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	/***
	 * 
	 * @param sheetName
	 *        sheetName
	 */
	private static void initHSSFWorkbook(String sheetName) {
		workbook = new HSSFWorkbook();
		sheet = workbook.createSheet(sheetName);
	}

	/**
	 * 生成标题(第零行创建)
	 * @param titleMap 对象属性名称->表头显示名称
	 * @param sheetName sheet名称
	 */
	private static void createTitleRow(Map<String, String> titleMap, String sheetName) {
		CellRangeAddress titleRange = new CellRangeAddress(0, 0, 0, titleMap.size() - 1);
		sheet.addMergedRegion(titleRange);
		HSSFRow titleRow = sheet.createRow(TITLE_START_POSITION);
		HSSFCell titleCell = titleRow.createCell(0);
		titleCell.setCellValue(sheetName);
	}

	/**
	 * 创建时间行(第一行创建)
	 * @param titleMap 对象属性名称->表头显示名称
	 */
	private static void createDateHeadRow(Map<String, String> titleMap) {
		CellRangeAddress dateRange = new CellRangeAddress(1, 1, 0, titleMap.size() - 1);
		sheet.addMergedRegion(dateRange);
		HSSFRow dateRow = sheet.createRow(DATEHEAD_START_POSITION);
		HSSFCell dateCell = dateRow.createCell(0);   
		dateCell.setCellValue(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
	}

	/**
	 * 创建表头行(第二行创建)
	 * @param titleMap 对象属性名称->表头显示名称
	 */
	private static void createHeadRow(Map<String, String> titleMap) {
		// 第1行创建
		HSSFRow headRow = sheet.createRow(HEAD_START_POSITION);
		int i = 0;
		for (String entry : titleMap.keySet()) {
			HSSFCell headCell = headRow.createCell(i);
			headCell.setCellValue(titleMap.get(entry));
			i++;
		}
	}

	/**
	 * 
	 * @param dataList 对象数据集合
	 * @param titleMap 表头信息
	 */
	private static void createContentRow(List<?> dataList, Map<String, String> titleMap) {
		try {
			int i=0;
			for (Object obj : dataList) {
				HSSFRow textRow = sheet.createRow(CONTENT_START_POSITION + i);
				int j = 0;
				for (String entry : titleMap.keySet()) {
					String method = "get" + entry.substring(0, 1).toUpperCase() + entry.substring(1);
					Method m = null ;
					for(Class<?> clazz = obj.getClass(); clazz != Object.class ; clazz = clazz.getSuperclass()) {
						try {    
							m = clazz.getDeclaredMethod(method, null) ;    
						} catch (Exception e) {  
						}
					}
					String value = m.invoke(obj, null).toString();
					HSSFCell textcell = textRow.createCell(j);
					
					sheet.setColumnWidth(j, letterCount(value,750,250));
					textcell.setCellValue(value);
					j++;
				}
				i++;
			}
		}catch (Exception e) {
		}
	}



	/**
	 * 自动伸缩列(如非必要,请勿打开此方法,耗内存)
	 * @param size 列数
	 */
	private static void autoSizeColumn(Integer size) { 
		for (int j = 0; j < size; j++) {
			//			sheet.autoSizeColumn(j);
			sheet.setColumnWidth(j, 256*size+184);
		}
	}


	/**创建文件夹**/
	public static String createDir(String destDirName){
		File dir = new File(destDirName);  
		//        if (!dir.exists()) {  
		if (!destDirName.endsWith(File.separator)) {  
			destDirName = destDirName + File.separator;  
		}
		dir.mkdirs();
		//        }
		return destDirName;  
	}


	/**计算内容含有字体个数**/
	private static int letterCount(String message,int chinese_len,int other_len){
		if(message ==null){
			return 1;
		}
		Pattern p = Pattern.compile("[\u4E00-\u9FA5]+");  
		Matcher m = p.matcher(message);  
		int zm=0;
		int num=0;
		int chinese=0;
		int other=0;
		char [] ch = message.toCharArray();
		for(int i=0;i<ch.length;i++){
			if((ch[i]>='a' && ch[i]<='z') || (ch[i]>='A' && ch[i]<='Z')){
				zm=zm+1;
			}else if(ch[i]>47 && ch[i]<58){
				num=num+1;
			}if(m.find()){
				chinese=chinese+m.group(0).length()+1;
			}else{
				other=other+1;
				other=(other-chinese)<=0?1:(other-chinese);
			}
		}
		int totalcount=(chinese*chinese_len)+(zm+num+(other))*other_len;
		return totalcount;
	}
	


}

转载于:https://my.oschina.net/v512345/blog/842016

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值