通用的excel导入导出类

news/2024/7/21 5:00:24 标签: excel

原文链接:http://www.iteye.com/topic/657977icon-default.png?t=LA92http://www.iteye.com/topic/657977

闲来无事,做了一个通用的excel导入导出类。 

可以在数据库查询过滤的基础上导出数据(只需传入过滤后的List即可), 
也可根据编辑的excel对数据库进行导入。引用了apache的poi,测试5000条数据的导入导出均在300毫秒左右 

Java代码  收藏代码

  1. package com.love;  
  2.   
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. /** 
  9.  * 作者:王云权;QQ:1371392495,email:wangyunquan@live.com 
  10.  *  欢迎转载;转载时请著名出处 
  11.  *  
  12.  */  
  13. @Retention(RetentionPolicy.RUNTIME)  
  14. @Target(ElementType.FIELD)  
  15. public @interface ExcelAnnotation {  
  16.     // excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入  
  17.     public String exportName();  
  18. }  



导出类 

Java代码  收藏代码

  1. package com.love;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.OutputStream;  
  5. import java.lang.reflect.Field;  
  6. import java.lang.reflect.Method;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.ArrayList;  
  9. import java.util.Collection;  
  10. import java.util.Date;  
  11. import java.util.Iterator;  
  12. import java.util.List;  
  13.   
  14. import org.apache.poi.hssf.usermodel.HSSFCell;  
  15. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  16. import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
  17. import org.apache.poi.hssf.usermodel.HSSFRow;  
  18. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  19. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  20.   
  21. /** 
  22.  * 作者:王云权;QQ:1371392495,email:wangyunquan@live.com 
  23.  *  欢迎转载;转载时请著名出处 
  24.  *  
  25.  */  
  26. public class ExcelExport<T> {  
  27.     /** 
  28.      *  
  29.      * @param title 标题 
  30.      * @param dataset 集合 
  31.      * @param out  输出流 
  32.      */  
  33.     public void exportExcel(String title, Collection<T> dataset,  
  34.             OutputStream out) {  
  35.         // 声明一个工作薄  
  36.         try {  
  37.             //首先检查数据看是否是正确的  
  38.             Iterator<T> its = dataset.iterator();  
  39.             if(dataset==null||!its.hasNext()||title==null||out==null)  
  40.             {  
  41.                 throw new Exception("传入的数据不对!");  
  42.             }  
  43.               
  44.             T ts = (T) its.next();  
  45.               
  46.             HSSFWorkbook workbook = new HSSFWorkbook();  
  47.             // 生成一个表格  
  48.             HSSFSheet sheet = workbook.createSheet(title);  
  49.             // 设置表格默认列宽度为15个字节  
  50.             sheet.setDefaultColumnWidth(15);  
  51.             // 生成一个样式  
  52.             HSSFCellStyle style = workbook.createCellStyle();  
  53.             // 设置标题样式  
  54.             style = ExcelStyle.setHeadStyle(workbook, style);  
  55.             // 生成并设置主体样式  
  56.             HSSFCellStyle style2 = workbook.createCellStyle();  
  57.             style2 = ExcelStyle.setbodyStyle(workbook, style2);  
  58.             // 得到所有字段  
  59.           
  60.             Field filed[] = ts.getClass().getDeclaredFields();  
  61.             // 标题  
  62.             List<String> exportfieldtile = new ArrayList<String>();  
  63.             // 导出的字段  
  64.             List<String> fiedName = new ArrayList<String>();  
  65.             // 遍历整个filed  
  66.             for (int i = 0; i < filed.length; i++) {  
  67.                 Field f = filed[i];  
  68.                 ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);  
  69.                 // 如果设置了annottion  
  70.                 if (exa != null) {  
  71.                     String exprot = exa.exportName();  
  72.                     // 添加到标题  
  73.                     exportfieldtile.add(exprot);  
  74.                     // 添加到需要导出的字段  
  75.                     fiedName.add(f.getName());  
  76.                 }  
  77.             }  
  78.             // 产生表格标题行  
  79.             HSSFRow row = sheet.createRow(0);  
  80.             for (int i = 0; i < exportfieldtile.size(); i++) {  
  81.                 HSSFCell cell = row.createCell(i);  
  82.                 cell.setCellStyle(style);  
  83.                 HSSFRichTextString text = new HSSFRichTextString(  
  84.                         exportfieldtile.get(i));  
  85.                 cell.setCellValue(text);  
  86.             }  
  87.   
  88.             Iterator<T> it = dataset.iterator();  
  89.             int index = 0;  
  90.             // 循环整个集合  
  91.             while (it.hasNext()) {  
  92.                 index++;  
  93.                 row = sheet.createRow(index);  
  94.                 T t = (T) it.next();  
  95.                 for (int k = 0; k < fiedName.size(); k++) {  
  96.                     HSSFCell cell = row.createCell(k);  
  97.                     String fieldname = fiedName.get(k);  
  98.                     String getMethodName = "get"  
  99.                             + fieldname.substring(01).toUpperCase()  
  100.                             + fieldname.substring(1);  
  101.                     Class tCls = t.getClass();  
  102.                     Method getMethod = tCls.getMethod(getMethodName,  
  103.                             new Class[] {});  
  104.                     Object value = getMethod.invoke(t, new Object[] {});  
  105.   
  106.                     String textValue = getValue(value);  
  107.   
  108.                     HSSFRichTextString richString = new HSSFRichTextString(  
  109.                             textValue);  
  110.                     cell.setCellValue(richString);  
  111.                 }  
  112.   
  113.             }  
  114.             workbook.write(out);  
  115.         } catch (Exception e) {  
  116.             e.printStackTrace();  
  117.         }  
  118.   
  119.     }  
  120.   
  121.     public String getValue(Object value) {  
  122.         String textValue = "";  
  123.         if (value == null)  
  124.             return textValue;  
  125.   
  126.         if (value instanceof Boolean) {  
  127.             boolean bValue = (Boolean) value;  
  128.             textValue = "是";  
  129.             if (!bValue) {  
  130.                 textValue = "否";  
  131.             }  
  132.         } else if (value instanceof Date) {  
  133.             Date date = (Date) value;  
  134.             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  135.             textValue = sdf.format(date);  
  136.         } else  
  137.             textValue = value.toString();  
  138.   
  139.         return textValue;  
  140.     }  
  141.   
  142.     public static void main(String[] args) throws Exception {  
  143.         List list = new ArrayList();  
  144.         for (int i = 0; i < 5000; i++) {  
  145.             Loginfo log = new Loginfo();  
  146.             log.setLogInfo("测试一下");  
  147.             log.setUserip("127.0.1.1");  
  148.             log.setUsername("测试");  
  149.             list.add(log);  
  150.         }  
  151.         OutputStream out = new FileOutputStream("D:\\testOne.xls");  
  152.         Long l = System.currentTimeMillis();  
  153.         ExcelExport<Loginfo> ex = new ExcelExport<Loginfo>();  
  154.         ex.exportExcel("测试", list, out);  
  155.         out.close();  
  156.         Long s = System.currentTimeMillis();  
  157.         System.out.println("总共耗时:" + (s - l));  
  158.   
  159.     }  
  160. }  




导入类: 

Java代码  收藏代码

  1. package com.love;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.lang.reflect.Field;  
  6. import java.lang.reflect.Method;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.ArrayList;  
  9. import java.util.Collection;  
  10. import java.util.Date;  
  11. import java.util.HashMap;  
  12. import java.util.Iterator;  
  13. import java.util.List;  
  14. import java.util.Map;  
  15.   
  16. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  17. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  18. import org.apache.poi.ss.usermodel.Cell;  
  19. import org.apache.poi.ss.usermodel.Row;  
  20.   
  21. /** 
  22.  * 作者:王云权;QQ:1371392495,email:wangyunquan@live.com 
  23.  *  欢迎转载;转载时请著名出处 
  24.  *  
  25.  */  
  26. public class ImportExcel<T> {  
  27.     Class<T> clazz;  
  28.   
  29.     public ImportExcel(Class<T> clazz) {  
  30.         this.clazz = clazz;  
  31.     }  
  32.   
  33.     public Collection<T> importExcel(File file ,String...  pattern) {  
  34.         Collection<T> dist = new ArrayList();  
  35.         try {  
  36.             /** 
  37.              * 类反射得到调用方法 
  38.              */  
  39.             // 得到目标目标类的所有的字段列表  
  40.             Field filed[] = clazz.getDeclaredFields();  
  41.             // 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中  
  42.             Map fieldmap = new HashMap();  
  43.             // 循环读取所有字段  
  44.             for (int i = 0; i < filed.length; i++) {  
  45.                 Field f = filed[i];  
  46.                 // 得到单个字段上的Annotation  
  47.                 ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);  
  48.                 // 如果标识了Annotationd的话  
  49.                 if (exa != null) {  
  50.                     // 构造设置了Annotation的字段的Setter方法  
  51.                     String fieldname = f.getName();  
  52.                     String setMethodName = "set"  
  53.                             + fieldname.substring(01).toUpperCase()  
  54.                             + fieldname.substring(1);  
  55.                     // 构造调用的method,  
  56.                     Method setMethod = clazz.getMethod(setMethodName,  
  57.                             new Class[] { f.getType() });  
  58.                     // 将这个method以Annotaion的名字为key来存入。  
  59.                     fieldmap.put(exa.exportName(), setMethod);  
  60.                 }  
  61.             }  
  62.             /** 
  63.              * excel的解析开始 
  64.              */  
  65.             // 将传入的File构造为FileInputStream;  
  66.             FileInputStream in = new FileInputStream(file);  
  67.             // // 得到工作表  
  68.             HSSFWorkbook book = new HSSFWorkbook(in);  
  69.             // // 得到第一页  
  70.             HSSFSheet sheet = book.getSheetAt(0);  
  71.             // // 得到第一面的所有行  
  72.             Iterator<Row> row = sheet.rowIterator();  
  73.   
  74.             /** 
  75.              * 标题解析 
  76.              */  
  77.             // 得到第一行,也就是标题行  
  78.             Row title = row.next();  
  79.             // 得到第一行的所有列  
  80.             Iterator<Cell> cellTitle = title.cellIterator();  
  81.             // 将标题的文字内容放入到一个map中。  
  82.             Map titlemap = new HashMap();  
  83.             // 从标题第一列开始  
  84.             int i = 0;  
  85.             // 循环标题所有的列  
  86.             while (cellTitle.hasNext()) {  
  87.                 Cell cell = cellTitle.next();  
  88.                 String value = cell.getStringCellValue();  
  89.                 titlemap.put(i, value);  
  90.                 i = i + 1;  
  91.             }  
  92.             /** 
  93.              * 解析内容行 
  94.              */  
  95.             //用来格式化日期的DateFormat  
  96.             SimpleDateFormat sf;  
  97.             if(pattern.length<1)  
  98.             {  
  99.                 sf=new SimpleDateFormat("yyyy-MM-dd");    
  100.             }  
  101.             else  
  102.                 sf=new SimpleDateFormat(pattern[0]);      
  103.             while (row.hasNext()) {  
  104.                 // 标题下的第一行  
  105.                 Row rown = row.next();  
  106.   
  107.                 // 行的所有列  
  108.                 Iterator<Cell> cellbody = rown.cellIterator();  
  109.                 // 得到传入类的实例  
  110.                 T tObject = clazz.newInstance();  
  111.                 int k = 0;  
  112.                 // 遍历一行的列  
  113.                 while (cellbody.hasNext()) {  
  114.                     Cell cell = cellbody.next();  
  115.                     // 这里得到此列的对应的标题  
  116.                     String titleString = (String) titlemap.get(k);  
  117.                     // 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值  
  118.                     if (fieldmap.containsKey(titleString)) {  
  119.                         Method setMethod = (Method) fieldmap.get(titleString);  
  120.                         //得到setter方法的参数  
  121.                         Class<?>[] ts = setMethod.getParameterTypes();  
  122.                         //只要一个参数  
  123.                         Object xclass = ts[0];  
  124.                         //判断参数类型  
  125.                         if(xclass instanceof String)  
  126.                         {  
  127.                             setMethod.invoke(tObject, cell.getStringCellValue());  
  128.                         }  
  129.                         else if(xclass instanceof Date)  
  130.                         {  
  131.                             setMethod.invoke(tObject, sf.parse(cell.getStringCellValue()));  
  132.                         }  
  133.                         else if(xclass instanceof Boolean)  
  134.                         {  
  135.                             String boolname="是";  
  136.                             if(cell.getStringCellValue().equals("否"))  
  137.                                 {  
  138.                                 boolname="否";  
  139.                                 }  
  140.                             setMethod.invoke(tObject,boolname );  
  141.                         }  
  142.                     }  
  143.                     // 下一列  
  144.                     k = k + 1;  
  145.                 }  
  146.                 dist.add(tObject);  
  147.             }  
  148.         } catch (Exception e) {  
  149.             e.printStackTrace();  
  150.             return null;  
  151.         }  
  152.         return dist;  
  153.     }  
  154.   
  155.     public static void main(String[] args) {  
  156.         ImportExcel<Loginfo> test = new ImportExcel(Loginfo.class);  
  157.         File file = new File("D:\\testOne.xls");  
  158.         Long befor = System.currentTimeMillis();  
  159.         List<Loginfo> result = (ArrayList) test.importExcel(file);  
  160.   
  161.         Long after = System.currentTimeMillis();  
  162.         System.out.println("此次操作共耗时:" + (after - befor) + "毫秒");  
  163.         // for (int i = 0; i < result.size(); i++) {  
  164.         // Loginfo loginfo=result.get(i);  
  165.         // System.out.println("导入的信息为:"+loginfo.getLogInfo()+loginfo.getUserip()+loginfo.getUsername());  
  166.         // }  
  167.   
  168.         System.out.println("共转化为List的行数为:" + result.size());  
  169.     }  
  170. }  
    1. package com.love;  
    2.   
    3.   
    4.   
    5. /** 
    6.  * 作者:王云权;QQ:1371392495,email:wangyunquan@live.com 
    7.  *  欢迎转载;转载时请著名出处 
    8.  *  
    9.  */  
    10.   
    11. public class Loginfo {  
    12.     @ExcelAnnotation(exportName = "用户IP地址")  
    13.     private String userip;  
    14.     @ExcelAnnotation(exportName = "用户姓名")  
    15.     private String username;  
    16.     @ExcelAnnotation(exportName = "操作信息")  
    17.     private String logInfo;  
    18.   
    19.     /** 
    20.      * @return the userip 
    21.      */  
    22.     public String getUserip() {  
    23.         return userip;  
    24.     }  
    25.     /** 
    26.      * @param userip the userip to set 
    27.      */  
    28.     public void setUserip(String userip) {  
    29.         this.userip = userip;  
    30.     }  
    31.     /** 
    32.      * @return the username 
    33.      */  
    34.     public String getUsername() {  
    35.         return username;  
    36.     }  
    37.     /** 
    38.      * @param username the username to set 
    39.      */  
    40.     public void setUsername(String username) {  
    41.         this.username = username;  
    42.     }  
    43.     /** 
    44.      * @return the logInfo 
    45.      */  
    46.     public String getLogInfo() {  
    47.         return logInfo;  
    48.     }  
    49.     /** 
    50.      * @param logInfo the logInfo to set 
    51.      */  
    52.     public void setLogInfo(String logInfo) {  
    53.         this.logInfo = logInfo;  
    54.     }  
    55.       
    56. }  

http://www.niftyadmin.cn/n/1111582.html

相关文章

推荐一个 可以和 Entity Framework 媲美 的 国人 写的 ORM

https://github.com/2881099/FreeSql 扶摇直上&#xff0c;至强ORM只为自由编码&#xff1b;鹏程万里&#xff0c;至简Linq可使保留黑发&#xff1b;横批&#xff1a;FreeSql&#xff08;诗人&#xff1a;Coder&#xff09; 即兴赋诗一首 ----------------------------- 以上是…

[UE4]HorizontalBox,整体向右对齐

转载于:https://www.cnblogs.com/timy/p/9062682.html

机器学习实战-边学边读python代码(3)

程序清单2-3 归一化特征值&#xff1a; def autoNorm(dataSet): /* >>> barray([[ 1., 2., 3.], [ 2., 3., 4.], [ 10., 0., 0.]])>>> b.max(0)array([ 10., 3., 4.])>>> b.min(0)array([ 1., 0., 0.]) 如上面的例子&#xff0c;求每一列的最大值(或…

性能测试术语

1. 并发数注册用户数&#xff1a;注册的所有用户在线用户数&#xff1a;在线的用户&#xff0c;但不一定和服务器有交互并发用户数&#xff1a;在线的用户&#xff0c;且必须和服务器有交互&#xff0c;LoadRunner中指的就是虚拟用户数&#xff0c;JMeter中的线程数2. 事务Tran…

eclipse 使用jetty调试时,加依赖工程的源码调试方法

[1] 添加source eclipse-->debug as-->debug configurations-->source [2]若source不起作用 重新编译一下&#xff0c;mvn clean install即可

JSON的使用小结

JSON中存储的是key:value&#xff0c;其实在编程的时候我们会遇到很多都是key:value的形式。比如&#xff1a;map,java对象&#xff08;一个对象的一个属性只会有一个值&#xff09;&#xff0c;数据库中key:value对应着里面存储的一个数据&#xff0c;redis的本质就是key:valu…

Linux--网络服务--DHCP服务,理论+实验(了解DHCP服务,DHCP工作原理,DHCP服务器的配置,DHCP客户端使用方法,以及DHCP配置实验详解)

Linux--网络服务--DHCP服务,理论实验&#xff08;了解DHCP服务&#xff0c;DHCP工作原理&#xff0c;DHCP服务器的配置&#xff0c;DHCP客户端使用方法&#xff0c;以及DHCP配置实验详解&#xff09;一&#xff1a;了解DHCP服务1.1&#xff1a;DHCP概述1.2&#xff1a;使用DHCP…

构建现代化网站的 20 个技巧(转)

英文原文&#xff1a;20 tips for building modern sites 在过去几年中&#xff0c;我们与web开发者花了很多时间交流&#xff0c;听得最多的一件事情就是创建一个能很好的跨越各种类型浏览器版本与各种设备的网站有多么难。我们为 jQuery项目写代码的时候一直有这个问题。因此…