excel导出模板实现动态封装字段再次升级【工具包系列】

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

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 ExcellUtil {

	/**
	 * 指定文件导出位置,导出excel
	 * @param sheetTitle sheet名称
	 * @param headers excel表头
	 * @param dataset 数据
	 * @param filePath 文件路径
	 * @param fields  需要导出的字段
	 * @return
	 * @create 2016-5-18 上午10:08:19
	 */
	public static boolean exportExcel(String sheetTitle, String[] headers,
			List<?> dataset, String filePath, String[] fields) {
		 		 OutputStream out = null;
			try {
				out = new FileOutputStream(filePath);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
				return false;
			}
		return	exportExcelByOS(sheetTitle, headers, dataset, out, fields);
	}
	
	/**
	 * 通过传入流生成excel
	 * @param sheetTitle sheet名称
	 * @param headers  excel表头
	 * @param dataset  数据
	 * @param out   流
	 * @param fields 需要导出的字段【TradeRecord中对应的字段】
	 * @return
	 * @create 2016-5-18 上午10:07:04
	 */
	@SuppressWarnings("deprecation")
	public static boolean exportExcelByOS(String sheetTitle, String[] headers,
			List<?> dataset, OutputStream out, String[] fields) {
		boolean flag = true;
		
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(sheetTitle);
		// 设置表格默认列宽度为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);
		// 生成并设置另一个样式
//		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);
//		 声明一个画图的顶级管理器
//		HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
		// 定义注释的大小和位置,详见文档
//		HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
//				0, 0, 0, (short) 4, 2, (short) 6, 5));
		// 设置注释内容
//		comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
		// 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
//		comment.setAuthor("leno");
		// 产生表格标题行
		HSSFRow row = sheet.createRow(0);
		int index = 0;
		//如果传入的表头是空或者长度为0 则 不需要表头
		if(headers==null||headers.length==0){
			index = -1;
		}else{
			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);
			}
		}
		if(dataset!=null){
			//循环集合
			for (Object info : dataset) {
				index++;
				row = sheet.createRow(index);
				for (int i = 0; i < fields.length; i++) {
					HSSFCell cell = row.createCell(i);
//					cell.setCellStyle(style2);
					cell.setCellValue(getFieldValue(info,fields[i]));
				}
			}
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			flag = false;
			e.printStackTrace();
		}finally{
			if(out!=null){
				try {
					out.close();
					out = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}
	
	
	
	
	/**
	 * 根据字段名称  获取对象中改字段的值
	 * @param obj 对象
	 * @param fieldName 字段
	 * @return
	 * @create 2016-5-17 下午1:04:19
	 */
	 public static String getFieldValue(Object obj,String fieldName) {
		 String value = null;
		 if (obj == null)   return null;  
	        Field[] fields = obj.getClass().getDeclaredFields(); 
	       
	        for (int j = 0; j < fields.length; j++) {
	        	fields[j].setAccessible(true);  
	        	if(fieldName.equals(fields[j].getName())){
	        		//改字段的类型
	        		String className = fields[j].getType().getName();
	        		try {
		        		//如果是日期类型 则转化
		        		if(className.equalsIgnoreCase("Date")||className.equalsIgnoreCase("java.util.Date")){
		        			Date time =  (Date) fields[j].get(obj);
		        			value = DateUtil.formatDate("yyyy-MM", time);
		        		}else{
		        			value =   fields[j].get(obj)==null?"":fields[j].get(obj)+"";
		        		}
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
	        	}
	        }
	      return value;  
	 }
	
}

这样写的好处就是再也不用管外面传给我们是什么对象了,都可以处理,下面我们来简单的调用一下

首先创建一个类,User.java

import java.util.Date;

public class User {
	//id
	private long id;
	//名字
	private String name;
	//密码
	private String password;
	//性别
	private String sex;
	//出生日期
	private Date born;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Date getBorn() {
		return born;
	}

	public void setBorn(Date born) {
		this.born = born;
	}
}

然后我们就通过这个类去实现导出效果

测试代码如下:


public class ExcellUtilTest {

	public static void main(String[] args) {
		//一一对应
		String[] headers = {"名字","密码","性别","出生日期"};
		String[] fields = {"name","password","sex","born"};
		
		List<User> users = new ArrayList<>();
		for (int i = 0; i < 5; i++) {
			User user = new User();
			user.setName("jack"+i);
			user.setPassword(i+"");
			user.setBorn(new Date());
			user.setSex(i%2==0?"男":"女");
			users.add(user);
		}
		
		ExcellUtil.exportExcel("用户信息", headers, users, "d:1.xls", fields);
		
	}
	
}

查看运行结果:




就是这么简单,对于时间或者特殊类型的操作,可以在工具类中的getFieldValue()方法中设置

,这个方法还有一个好处就是可以实现动态导出报表,表头和字段只要一一对应上,数量不限(只限制本类中的属性)






  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值