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

来源:互联网 发布:淘宝买药付款流程 编辑:程序博客网 时间:2024/05/22 03:47
转发一个通用的导入导出组件 

请注意:导入导出功能是通过自定义的Annotattion来实现的,要将pojo中的字段的类标注指定的annotation才可以,如果没有标注的,就默认不导出导入

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

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

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

所用到的jar包: http://download.csdn.net/detail/liaoqianwen123/6815415

Java代码:

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];// 得到单个字段上的AnnotationExcelAnnotation 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;}/** * 解析内容行 *///用来格式化日期的DateFormatSimpleDateFormat sf;if(pattern.length<1){sf=new SimpleDateFormat("yyyy-MM-dd");}elsesf=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>();// 遍历整个filedfor (int i = 0; i < filed.length; i++) {Field f = filed[i];ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);// 如果设置了annottionif (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);} elsetextValue = 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));}}

http://www.iteye.com/topic/680586

0 0
原创粉丝点击