POI导入导出Excel

package com.byd.core;

import java.io.File;package com.byd.core;

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;  

public class ExcelExport<T> {
	 //格式化日期   
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
    /**  
     *   
     * @param title 标题  
     * @param dataset 集合  
     * @param out  输出流  
     */  
    @SuppressWarnings("unchecked")
	public void exportExcel(String title, Collection<T> dataset,   
            OutputStream out) {   
        // 声明一个工作薄   
        try {   
            //首先检查数据看是否是正确的   
            Iterator<T> its = dataset.iterator();   
            System.out.println(dataset.size());
	            if(dataset==null||!its.hasNext()||title==null||out==null)   
	            {   
	                throw new Exception("传入的数据不对!");   
	            }   
	            //取得实际泛型类 
	            int index = 0; 
	            HSSFWorkbook workbook = new HSSFWorkbook();   
	            // 生成一个表格   
	            HSSFSheet sheet = workbook.createSheet(title);   
	            List<Method> methodObj = new ArrayList<Method>();
	           while (its.hasNext()) {
	              index++; 
	              T ts = (T) its.next(); 
	              if (index==1){  
		            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);  
		                System.out.println(text);
		            }   
	           }
	         
	               
	            // 循环整个集合   
	               
	            //while (its.hasNext()) {   
	                //从第二行开始写,第一行是标题   
	               // index++;   
	              HSSFRow 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(ts, 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));   
  
    }   */
}  

 
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;
public class ImportExcel<T> {
		Class<T> clazz;

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

		@SuppressWarnings("unchecked")
		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 String exportDate(String fileName,String rootPath,Collection<T> dataset,OutputStream out) throws UnsupportedEncodingException{
		String xlsPath = rootPath + "main\\download\\"+fileName+".xls";
		String path="download/"+fileName+".xls";
		String down =new String(path.getBytes(),"utf-8");
		File file = new File(xlsPath + "\\main\\download\\");
		if (file.listFiles() != null) {
			for (int i = 0; i < file.listFiles().length; i++) {
				if (file.listFiles()[i].getName().endsWith(".xls")){
					boolean flag=file.listFiles()[i].delete();
					if(flag){
						try {
							 out = new FileOutputStream(rootPath
									+ "\\main\\download\\" + fileName + ".xls");
							this.exportExcel(fileName, dataset, out);
							out.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return down;
    }
		/*public static void main(String[] args) {
			ImportExcel<Testpojo> test = new ImportExcel(Testpojo.class);
			File file = new File("D:\\order.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());
		}*/
 }
package com.byd.core;
import java.lang.annotation.ElementType;   
import java.lang.annotation.Retention;   
import java.lang.annotation.RetentionPolicy;   
import java.lang.annotation.Target;   
  
  
@Retention(RetentionPolicy.RUNTIME)   
@Target(ElementType.FIELD)   
public @interface ExcelAnnotation {   
    // excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入   
    public String exportName();   
}  

private Integer id;
      private String workplace;
   @ExcelAnnotation(exportName="工段")
   private String station;
   @ExcelAnnotation(exportName="线别")
   private String line;
   @ExcelAnnotation(exportName="机型")
   private String phonetype;
   @ExcelAnnotation(exportName="节拍")
   private Integer beat;
   @ExcelAnnotation(exportName="标准作业时间")
   private Integer workinghours;
   @ExcelAnnotation(exportName="标准人数")
   private Integer workers;
   private Integer output;
   @ExcelAnnotation(exportName="标准UPH值")
   private String uph;
   private String upph;


 

posted @ 2011-06-16 10:14  上善¤若水  阅读(283)  评论(0编辑  收藏  举报