论坛首页 Java企业应用论坛

发一个通用从数据库导出excel、excel导入数据库组件

浏览 24135 次
精华帖 (0) :: 良好帖 (4) :: 新手帖 (18) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-06-01  
以前发过一次,看见许多朋友都很需要这种通用的导入导出组件
请注意:导入导出功能是通过自定义的Annotattion来实现的,要将pojo中的字段的类标注指定的annotation才可以,如果没有标注的,就默认不导出导入

一般情况下只需要简单的三步,就可以实现导入和导出了,要是你使用了hibernate,就会发现太方便了

一:
构造输入输出流 如: OutputStream out = new FileOutputStream("D:\\testOne.xls");
二,构造导入导出对象 如: ExcelExport<Testpojo> ex = new ExcelExport<Testpojo>();
三,操作  ex.exportExcel("测试", list, out);


当然,因为操作数据都是Connection接口的,所以,你可以在导入
导出之前对数据进行过滤、排序、分组等,到时候动态的传进去就可以了,实在非常的方便,废话不多说,直接上代码:


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


/**
 * 作者:eya;QQ:1371392495,email:eya@eya.cc
 *  欢迎转载;转载时请著名出处
 * 
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelAnnotation {
	// excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入
	public String exportName();
}






import java.util.Date;

/**
 * 作者:eya;QQ:1371392495,email:eya@eya.cc
 *  欢迎转载;转载时请著名出处
 * 
 */
public class Testpojo {
	@ExcelAnnotation(exportName = "用户名")
	String username;
	@ExcelAnnotation(exportName = "登录名")
	String loginname;
	@ExcelAnnotation(exportName = "年龄")
	Integer age;
	@ExcelAnnotation(exportName = "收入")
	Long   money;
	@ExcelAnnotation(exportName = "时间")
	Date createtime;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Long getMoney() {
		return money;
	}
	public void setMoney(Long money) {
		this.money = money;
	}
	public Date getCreatetime() {
		return createtime;
	}
	public void setCreatetime(Date createtime) {
		this.createtime = createtime;
	}
	

}








import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;


/**
 * 作者:eya;QQ:1371392495,email:eya@eya.cc
 *  欢迎转载;转载时请著名出处
 * 
 */
public class ExcelStyle {
	public static HSSFCellStyle setHeadStyle(HSSFWorkbook workbook ,HSSFCellStyle style)
	{
		
		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);
		return style;
		
	}
	public static HSSFCellStyle setbodyStyle(HSSFWorkbook workbook ,HSSFCellStyle style2)
	{
		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);
		return style2;
	}
}






import java.util.Date;

/**
 * 作者:eya;QQ:1371392495,email:eya@eya.cc
 *  欢迎转载;转载时请著名出处
 * 
 */
public class Testpojo {
	@ExcelAnnotation(exportName = "用户名")
	String username;
	@ExcelAnnotation(exportName = "登录名")
	String loginname;
	@ExcelAnnotation(exportName = "年龄")
	Integer age;
	@ExcelAnnotation(exportName = "收入")
	Long   money;
	@ExcelAnnotation(exportName = "时间")
	Date createtime;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Long getMoney() {
		return money;
	}
	public void setMoney(Long money) {
		this.money = money;
	}
	public Date getCreatetime() {
		return createtime;
	}
	public void setCreatetime(Date createtime) {
		this.createtime = createtime;
	}
	

}






import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

/**
 * 作者:eya;QQ:1371392495,email:eya@eya.cc
 *  欢迎转载;转载时请著名出处
 * 
 */
public class ImportExcel<T> {
	Class<T> clazz;

	public ImportExcel(Class<T> clazz) {
		this.clazz = clazz;
	}

	public Collection<T> importExcel(File file ,String...  pattern) {
		Collection<T> dist = new ArrayList();
		try {
			/**
			 * 类反射得到调用方法
			 */
			// 得到目标目标类的所有的字段列表
			Field filed[] = clazz.getDeclaredFields();
			// 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中
			Map fieldmap = new HashMap();
			// 循环读取所有字段
			for (int i = 0; i < filed.length; i++) {
				Field f = filed[i];
				// 得到单个字段上的Annotation
				ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
				// 如果标识了Annotationd的话
				if (exa != null) {
					// 构造设置了Annotation的字段的Setter方法
					String fieldname = f.getName();
					String setMethodName = "set"
							+ fieldname.substring(0, 1).toUpperCase()
							+ fieldname.substring(1);
					// 构造调用的method,
					Method setMethod = clazz.getMethod(setMethodName,
							new Class[] { f.getType() });
					// 将这个method以Annotaion的名字为key来存入。
					fieldmap.put(exa.exportName(), setMethod);
				}
			}
			/**
			 * excel的解析开始
			 */
			// 将传入的File构造为FileInputStream;
			FileInputStream in = new FileInputStream(file);
			// // 得到工作表
			HSSFWorkbook book = new HSSFWorkbook(in);
			// // 得到第一页
			HSSFSheet sheet = book.getSheetAt(0);
			// // 得到第一面的所有行
			Iterator<Row> row = sheet.rowIterator();

			/**
			 * 标题解析
			 */
			// 得到第一行,也就是标题行
			Row title = row.next();
			// 得到第一行的所有列
			Iterator<Cell> cellTitle = title.cellIterator();
			// 将标题的文字内容放入到一个map中。
			Map titlemap = new HashMap();
			// 从标题第一列开始
			int i = 0;
			// 循环标题所有的列
			while (cellTitle.hasNext()) {
				Cell cell = cellTitle.next();
				String value = cell.getStringCellValue();
				titlemap.put(i, value);
				i = i + 1;
			}
			/**
			 * 解析内容行
			 */
			//用来格式化日期的DateFormat
			SimpleDateFormat sf;
			if(pattern.length<1)
			{
				sf=new SimpleDateFormat("yyyy-MM-dd");	
			}
			else
				sf=new SimpleDateFormat(pattern[0]);	
			while (row.hasNext()) {
				// 标题下的第一行
				Row rown = row.next();

				// 行的所有列
				Iterator<Cell> cellbody = rown.cellIterator();
				// 得到传入类的实例
				T tObject = clazz.newInstance();
				int k = 0;
				// 遍历一行的列
				while (cellbody.hasNext()) {
					Cell cell = cellbody.next();
					// 这里得到此列的对应的标题
					String titleString = (String) titlemap.get(k);
					// 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值
					if (fieldmap.containsKey(titleString)) {
						Method setMethod = (Method) fieldmap.get(titleString);
						//得到setter方法的参数
						Type[] ts = setMethod.getGenericParameterTypes();
						//只要一个参数
						String xclass = ts[0].toString();
						//判断参数类型
						
					
						if(xclass. equals("class java.lang.String"))
						{
							setMethod.invoke(tObject, cell.getStringCellValue());
						}
						else if(xclass. equals("class java.util.Date"))
						{
							setMethod.invoke(tObject, sf.parse(cell.getStringCellValue()));
						}
						else if(xclass. equals("class java.lang.Boolean"))
						{
							Boolean boolname=true;
							if(cell.getStringCellValue().equals("否"))
								{
								boolname=false;
								}
							setMethod.invoke(tObject,boolname );
						}
						else if(xclass. equals("class java.lang.Integer"))
						{
							setMethod.invoke(tObject,new Integer( cell.getStringCellValue()));
						}
						
						else if(xclass. equals("class java.lang.Long"))
						{
							setMethod.invoke(tObject,new Long( cell.getStringCellValue()));
						}
					}
					// 下一列
					k = k + 1;
				}
				dist.add(tObject);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return dist;
	}

	public static void main(String[] args) {
		ImportExcel<Testpojo> test = new ImportExcel(Testpojo.class);
		File file = new File("D:\\testOne.xls");
		Long befor = System.currentTimeMillis();
		List<Testpojo> result = (ArrayList) test.importExcel(file);

		Long after = System.currentTimeMillis();
		System.out.println("此次操作共耗时:" + (after - befor) + "毫秒");
		 for (int i = 0; i < result.size(); i++) {
			 Testpojo testpojo=result.get(i);
		 System.out.println("导入的信息为:"+testpojo.getLoginname()+
				 "----"+testpojo.getAge()+"---"+testpojo.getMoney()+"-----"+testpojo.getCreatetime());
		 }

		System.out.println("共转化为List的行数为:" + result.size());
	}
}





import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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 cc.eya.base.entity.account.Loginfo;


/**
 * 作者:eya;QQ:1371392495,email:eya@eya.cc
 *  欢迎转载;转载时请著名出处
 * 
 */
public class ExcelExport<T> {
	//格式化日期
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 
	 * @param title 标题
	 * @param dataset 集合
	 * @param out  输出流
	 */
	public void exportExcel(String title, Collection<T> dataset,
			OutputStream out) {
		// 声明一个工作薄
		try {
			//首先检查数据看是否是正确的
			Iterator<T> its = dataset.iterator();
			if(dataset==null||!its.hasNext()||title==null||out==null)
			{
				throw new Exception("传入的数据不对!");
			}
			//取得实际泛型类
			T ts = (T) its.next();
			Class tCls = ts.getClass();
			HSSFWorkbook workbook = new HSSFWorkbook();
			// 生成一个表格
			HSSFSheet sheet = workbook.createSheet(title);
			// 设置表格默认列宽度为15个字节
			sheet.setDefaultColumnWidth(15);
			// 生成一个样式
			HSSFCellStyle style = workbook.createCellStyle();
			// 设置标题样式
			style = ExcelStyle.setHeadStyle(workbook, style);

			// 得到所有字段
		
			Field filed[] = ts.getClass().getDeclaredFields();
			// 标题
			List<String> exportfieldtile = new ArrayList<String>();
			// 导出的字段的get方法
			List<Method> methodObj = new ArrayList<Method>();
			// 遍历整个filed
			for (int i = 0; i < filed.length; i++) {
				Field f = filed[i];
				ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
				// 如果设置了annottion
				if (exa != null) {
					String exprot = exa.exportName();
					// 添加到标题
					exportfieldtile.add(exprot);
					// 添加到需要导出的字段的方法
					String fieldname = f.getName();
					String getMethodName = "get"
							+ fieldname.substring(0, 1).toUpperCase()
							+ fieldname.substring(1);
					
					Method getMethod = tCls.getMethod(getMethodName,
							new Class[] {});
					
					
					methodObj.add(getMethod);
				}
			}
			// 产生表格标题行
			HSSFRow row = sheet.createRow(0);
			for (int i = 0; i < exportfieldtile.size(); i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellStyle(style);
				HSSFRichTextString text = new HSSFRichTextString(
						exportfieldtile.get(i));
				cell.setCellValue(text);
			}

	
			int index = 0;
			
			// 循环整个集合
			
			while (its.hasNext()) {
				//从第二行开始写,第一行是标题
				index++;
				row = sheet.createRow(index);
				T t = (T) its.next();
				for (int k = 0; k < methodObj.size(); k++) {
					HSSFCell cell = row.createCell(k);
					Method getMethod=methodObj.get(k);
					Object value = getMethod.invoke(t, new Object[] {});
					String textValue = getValue(value);
					cell.setCellValue(textValue);
				}

			}
			workbook.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public String getValue(Object value) {
		String textValue = "";
		if (value == null)
			return textValue;

		if (value instanceof Boolean) {
			boolean bValue = (Boolean) value;
			textValue = "是";
			if (!bValue) {
				textValue = "否";
			}
		} else if (value instanceof Date) {
			Date date = (Date) value;
		
			textValue = sdf.format(date);
		} else
			textValue = value.toString();

		return textValue;
	}

	public static void main(String[] args) throws Exception {
		
		//构造一个模拟的List来测试,实际使用时,这个集合用从数据库中查出来
		List list = new ArrayList();
		for (int i = 0; i < 5000; i++) {
			Testpojo pojo = new Testpojo();
			pojo.setLoginname("登录名"+i);
			pojo.setUsername("用户名"+i);
			pojo.setMoney(new Long(1000+i));
			pojo.setCreatetime(new Date());
		    pojo.setAge(28);
			list.add(pojo);
		}
		//构造输出对象,可以从response输出,直接向用户提供下载
		OutputStream out = new FileOutputStream("D:\\testOne.xls");
		//开始时间
		Long l = System.currentTimeMillis();
		//注意
		ExcelExport<Testpojo> ex = new ExcelExport<Testpojo>();
		//
		ex.exportExcel("测试", list, out);
		out.close();
		//结束时间
		Long s = System.currentTimeMillis();
		System.out.println("总共耗时:" + (s - l));

	}
}





  • lib.rar (8 MB)
  • 下载次数: 2386
   发表时间:2010-06-01  
还是很不错的想法 可以下载来试试
0 请登录后投票
   发表时间:2010-06-01  
allskylove 写道
哈哈,以前做过一个,同样是注解,方法反射调用,验证规则,转换规则。,导入导出,一般需要考虑 ,文件上传, 文件校验,字段校验(校验就比较多东西),还有字段类型转换,导入进度显示。出错处理等等。


把你的贴出来看看
0 请登录后投票
   发表时间:2010-06-01  
有图为证???
0 请登录后投票
   发表时间:2010-06-01   最后修改:2010-06-01
搞个同时支持excel2007和2003的
0 请登录后投票
   发表时间:2010-06-02  
这不是有现成的么?
0 请登录后投票
   发表时间:2010-06-02  
不是有jxl.jar包吗?还要自己写??
0 请登录后投票
   发表时间:2010-06-02   最后修改:2010-06-02
jxausea 写道
不是有jxl.jar包吗?还要自己写??

jxl太原始了,还需要手工操作

另请教一下,导入的时候如果数据很多,每次保存在list种是不是不太合适?
0 请登录后投票
   发表时间:2010-06-02  
JXL不是省事吗?

又学看其它的API

JPA查出来 JXL把结果生成出来 多灵活 又方便入手
0 请登录后投票
   发表时间:2010-06-02  
allskylove 写道
哈哈,以前做过一个,同样是注解,方法反射调用,验证规则,转换规则。,导入导出,一般需要考虑 ,文件上传, 文件校验,字段校验(校验就比较多东西),还有字段类型转换,导入进度显示。出错处理等等。


说说设计思路?如何实现规则验证,转换映射
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics