excel的导入与导出

 
  1. package cn.chn.chen.dev.excel;    
  2.   
  3. 02      
  4.   
  5. 03 import java.lang.annotation.ElementType;    
  6.   
  7. 04 import java.lang.annotation.Retention;    
  8.   
  9. 05 import java.lang.annotation.RetentionPolicy;    
  10.   
  11. 06 import java.lang.annotation.Target;    
  12.   
  13. 07      
  14.   
  15. 08 /**   
  16.  
  17. 09  * <p>   
  18.  
  19. 10  * ExcelAnnotation类主要用于-.   
  20.  
  21. 11  * </p>   
  22.  
  23. 12  * <p>   
  24.  
  25. 13  * 创建时间 2011-4-18 - 下午10:05:47   
  26.  
  27. 14  * </p>   
  28.  
  29. 15  * <blockquote>   
  30.  
  31. 16  * <h4>历史修改记录</h4>   
  32.  
  33. 17  * <ul>   
  34.  
  35. 18  * <li>修改人 修改时间 修改描述   
  36.  
  37. 19  * </ul>   
  38.  
  39. 20  * </blockquote>   
  40.  
  41. 21  * <p>   
  42.  
  43. 22  * copyright cd×××× 2010-2011, all rights reserved.   
  44.  
  45. 23  * </p>   
  46.  
  47. 24  *    
  48.  
  49. 25  * @author IT山人   
  50.  
  51. 26  * @since 1.0   
  52.  
  53. 27  * @version 1.0   
  54.  
  55. 28  */   
  56.   
  57. 29 @Retention(RetentionPolicy.RUNTIME)    
  58.   
  59. 30 @Target(ElementType.FIELD)    
  60.   
  61. 31 public @interface ExcelAnnotation {    
  62.   
  63. 32      // excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入     
  64.   
  65. 33     public String exportName();    
  66.   
  67. 34 }   
  68.   
  69. ExcelStyle.java;  
  70.   
  71. 01 package cn.chn.chen.dev.excel;    
  72.   
  73. 02      
  74.   
  75. 03 import org.apache.poi.hssf.usermodel.HSSFCellStyle;    
  76.   
  77. 04 import org.apache.poi.hssf.usermodel.HSSFFont;    
  78.   
  79. 05 import org.apache.poi.hssf.usermodel.HSSFWorkbook;    
  80.   
  81. 06 import org.apache.poi.hssf.util.HSSFColor;    
  82.   
  83. 07      
  84.   
  85. 08 /**   
  86.  
  87. 09  * <p>   
  88.  
  89. 10  * ExcelStyle类主要用于-excel导出样式控制.   
  90.  
  91. 11  * </p>   
  92.  
  93. 12  * <p>   
  94.  
  95. 13  * 创建时间 2011-4-21 - 下午12:43:11   
  96.  
  97. 14  * </p>   
  98.  
  99. 15  * @author IT山人   
  100.  
  101. 16  */   
  102.   
  103. 17 public class ExcelStyle {    
  104.   
  105. 18     public static HSSFCellStyle setHeadStyle(HSSFWorkbook workbook,    
  106.   
  107. 19             HSSFCellStyle style) {    
  108.   
  109. 20         style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);    
  110.   
  111. 21         style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);    
  112.   
  113. 22         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);    
  114.   
  115. 23         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);    
  116.   
  117. 24         style.setBorderRight(HSSFCellStyle.BORDER_THIN);    
  118.   
  119. 25         style.setBorderTop(HSSFCellStyle.BORDER_THIN);    
  120.   
  121. 26         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);    
  122.   
  123. 27         // 生成字体     
  124.   
  125. 28         HSSFFont font = workbook.createFont();    
  126.   
  127. 29         font.setColor(HSSFColor.VIOLET.index);    
  128.   
  129. 30         font.setFontHeightInPoints((short12);    
  130.   
  131. 31         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);    
  132.   
  133. 32         // 把字体应用到当前的样样式     
  134.   
  135. 33         style.setFont(font);    
  136.   
  137. 34         return style;    
  138.   
  139. 35      
  140.   
  141. 36     }    
  142.   
  143. 37      
  144.   
  145. 38     public static HSSFCellStyle setbodyStyle(HSSFWorkbook workbook,    
  146.   
  147. 39             HSSFCellStyle style) {    
  148.   
  149. 40         style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);    
  150.   
  151. 41         style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);    
  152.   
  153. 42         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);    
  154.   
  155. 43         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);    
  156.   
  157. 44         style.setBorderRight(HSSFCellStyle.BORDER_THIN);    
  158.   
  159. 45         style.setBorderTop(HSSFCellStyle.BORDER_THIN);    
  160.   
  161. 46         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);    
  162.   
  163. 47         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);    
  164.   
  165. 48         // 生成字体     
  166.   
  167. 49         HSSFFont font = workbook.createFont();    
  168.   
  169. 50         font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);    
  170.   
  171. 51         // 把字体应用到当前的样样式     
  172.   
  173. 52         style.setFont(font);    
  174.   
  175. 53         return style;    
  176.   
  177. 54     }    
  178.   
  179. 55 }   
  180. 1 ImportExcel.java;   
  181. 001 package cn.chn.chen.dev.excel;    
  182.   
  183. 002      
  184.   
  185. 003 import java.io.File;    
  186.   
  187. 004 import java.io.FileInputStream;    
  188.   
  189. 005 import java.lang.reflect.Field;    
  190.   
  191. 006 import java.lang.reflect.Method;    
  192.   
  193. 007 import java.lang.reflect.Type;    
  194.   
  195. 008 import java.text.SimpleDateFormat;    
  196.   
  197. 009 import java.util.ArrayList;    
  198.   
  199. 010 import java.util.Collection;    
  200.   
  201. 011 import java.util.HashMap;    
  202.   
  203. 012 import java.util.Iterator;    
  204.   
  205. 013 import java.util.List;    
  206.   
  207. 014 import java.util.Map;    
  208.   
  209. 015      
  210.   
  211. 016 import org.apache.poi.hssf.usermodel.HSSFSheet;    
  212.   
  213. 017 import org.apache.poi.hssf.usermodel.HSSFWorkbook;    
  214.   
  215. 018 import org.apache.poi.ss.usermodel.Cell;    
  216.   
  217. 019 import org.apache.poi.ss.usermodel.Row;    
  218.   
  219. 020      
  220.   
  221. 021 /**   
  222.  
  223. 022  * <p>   
  224.  
  225. 023  * ImportExcel类主要用于-Excel导入(POI).   
  226.  
  227. 024  * </p>   
  228.  
  229. 025  * <p>   
  230.  
  231. 026  * 创建时间 2011-4-18 - 下午10:33:52   
  232.  
  233. 027  * </p>   
  234.  
  235. 028  * @author IT山人   
  236.  
  237. 029  */   
  238.   
  239. 030 public class ImportExcel<T> {    
  240.   
  241. 031          
  242.   
  243. 032     Class<T> clazz;    
  244.   
  245. 033          
  246.   
  247. 034     public ImportExcel (Class<T> clazz) {    
  248.   
  249. 035         this.clazz = clazz;    
  250.   
  251. 036     }    
  252.   
  253. 037          
  254.   
  255. 038     public Collection<T> importExcel(File file, String...pattern) {    
  256.   
  257. 039         Collection<T> dist = new ArrayList<T>();    
  258.   
  259. 040         try {    
  260.   
  261. 041             /**   
  262.  
  263. 042              * 类反射得到调用方法   
  264.  
  265. 043              */   
  266.   
  267. 044             // 得到目标目标类的所有的字段列表       
  268.   
  269. 045             Field[] fields = clazz.getDeclaredFields();    
  270.   
  271. 046             // 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中     
  272.   
  273. 047             Map<String, Method> fieldMap = new HashMap<String, Method>();    
  274.   
  275. 048             // 循环读取所有字段     
  276.   
  277. 049             for (Field field : fields) {    
  278.   
  279. 050                 // 得到单个字段上的Annotation     
  280.   
  281. 051                 ExcelAnnotation excelAnnotation = field.getAnnotation(ExcelAnnotation.class);    
  282.   
  283. 052                 // 如果标识了Annotationd     
  284.   
  285. 053                 if (excelAnnotation != null) {    
  286.   
  287. 054                     String fieldName = field.getName();    
  288.   
  289. 055                     // 构造设置了Annotation的字段的Setter方法     
  290.   
  291. 056                     String setMethodName = "set" + fieldName.substring(01).toUpperCase() + fieldName.substring(1);    
  292.   
  293. 057                     // 构造调用的method     
  294.   
  295. 058                     Method setMethod = clazz.getMethod(setMethodName, new Class[] {field.getType()});    
  296.   
  297. 059                     // 将这个method以Annotaion的名字为key来存入     
  298.   
  299. 060                     fieldMap.put(excelAnnotation.exportName(), setMethod);    
  300.   
  301. 061                 }    
  302.   
  303. 062             }    
  304.   
  305. 063                  
  306.   
  307. 064             /**   
  308.  
  309. 065              * excel的解析开始   
  310.  
  311. 066              */   
  312.   
  313. 067             // 将传入的File构造为FileInputStream;     
  314.   
  315. 068             FileInputStream inputStream = new FileInputStream(file);    
  316.   
  317. 069             // 得到工作表     
  318.   
  319. 070             HSSFWorkbook book = new HSSFWorkbook(inputStream);    
  320.   
  321. 071             // 得到第一页     
  322.   
  323. 072             HSSFSheet sheet = book.getSheetAt(0);    
  324.   
  325. 073             // 得到第一面的所有行     
  326.   
  327. 074             Iterator<Row> row = sheet.rowIterator();    
  328.   
  329. 075                  
  330.   
  331. 076             /**   
  332.  
  333. 077              * 标题解析   
  334.  
  335. 078              */   
  336.   
  337. 079             // 得到第一行,也就是标题行     
  338.   
  339. 080             Row titleRow = row.next();    
  340.   
  341. 081             // 得到第一行的所有列     
  342.   
  343. 082             Iterator<Cell> cellTitle = titleRow.cellIterator();    
  344.   
  345. 083             // 将标题的文字内容放入到一个map中     
  346.   
  347. 084             Map<Integer, String> titleMap = new HashMap<Integer, String>();    
  348.   
  349. 085             // 从标题第一列开始     
  350.   
  351. 086             int i = 0;    
  352.   
  353. 087             // 循环标题所有的列     
  354.   
  355. 088             while (cellTitle.hasNext()) {    
  356.   
  357. 089                 Cell cell = (Cell) cellTitle.next();    
  358.   
  359. 090                 String value = cell.getStringCellValue();    
  360.   
  361. 091                 titleMap.put(i, value);    
  362.   
  363. 092                 i++;    
  364.   
  365. 093             }    
  366.   
  367. 094                  
  368.   
  369. 095             /**   
  370.  
  371. 096              * 解析内容行   
  372.  
  373. 097              */   
  374.   
  375. 098             while (row.hasNext()) {    
  376.   
  377. 099                 // 标题下的第一行     
  378.   
  379. 100                 Row rown = row.next();    
  380.   
  381. 101                 // 行的所有列     
  382.   
  383. 102                 Iterator<Cell> cellBody = rown.cellIterator();    
  384.   
  385. 103                 // 得到传入类的实例     
  386.   
  387. 104                 T tObject = clazz.newInstance();    
  388.   
  389. 105                 // 遍历一行的列     
  390.   
  391. 106                 int col = 0;    
  392.   
  393. 107                 while (cellBody.hasNext()) {    
  394.   
  395. 108                     Cell cell = (Cell) cellBody.next();    
  396.   
  397. 109                     // 这里得到此列的对应的标题     
  398.   
  399. 110                     String titleString = titleMap.get(col++);    
  400.   
  401. 111                     // 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值     
  402.   
  403. 112                     if (fieldMap.containsKey(titleString)) {    
  404.   
  405. 113                         Method setMethod = fieldMap.get(titleString);    
  406.   
  407. 114                         //得到setter方法的参数     
  408.   
  409. 115                         Type[] types = setMethod.getGenericParameterTypes();    
  410.   
  411. 116                         //只要一个参数     
  412.   
  413. 117                         String xclass = String.valueOf(types[0]);    
  414.   
  415. 118                         //判断参数类型     
  416.   
  417. 119                         if ("class java.lang.String".equals(xclass)) {    
  418.   
  419. 120                             setMethod.invoke(tObject, cell.getStringCellValue());    
  420.   
  421. 121                         } else if ("class java.util.Date".equals(xclass)) {    
  422.   
  423. 122                             setMethod.invoke(tObject, cell.getDateCellValue());    
  424.   
  425. 123                         } else if ("class java.lang.Boolean".equals(xclass)) {    
  426.   
  427. 124                             Boolean boolName = true;    
  428.   
  429. 125                             if ("否".equals(cell.getStringCellValue())) {    
  430.   
  431. 126                                 boolName = false;    
  432.   
  433. 127                             }    
  434.   
  435. 128                             setMethod.invoke(tObject, boolName);    
  436.   
  437. 129                         } else if ("class java.lang.Integer".equals(xclass)) {    
  438.   
  439. 130                             setMethod.invoke(tObject, new Integer(String.valueOf((int)cell.getNumericCellValue())));    
  440.   
  441. 131                         } else if ("class java.lang.Long".equals(xclass)) {    
  442.   
  443. 132                             setMethod.invoke(tObject, new Long(cell.getStringCellValue()));    
  444.   
  445. 133                         } else {    
  446.   
  447. 134                             //     
  448.   
  449. 135                         }    
  450.   
  451. 136                     }    
  452.   
  453. 137                 }    
  454.   
  455. 138                 dist.add(tObject);    
  456.   
  457. 139             }    
  458.   
  459. 140                  
  460.   
  461. 141         } catch (Exception e) {    
  462.   
  463. 142             // TODO: handle exception     
  464.   
  465. 143             e.printStackTrace();    
  466.   
  467. 144             return null;    
  468.   
  469. 145         }    
  470.   
  471. 146          return dist;    
  472.   
  473. 147     }    
  474.   
  475. 148          
  476.   
  477. 149     public static void main(String[] args) {    
  478.   
  479. 150         ImportExcel<TestVo> test = new ImportExcel<TestVo>(TestVo.class);    
  480.   
  481. 151         File file = new File("D:\\testOne.xls");    
  482.   
  483. 152         List<TestVo> results = (List<TestVo>) test.importExcel(file);    
  484.   
  485. 153         SimpleDateFormat simpleDateFormat;       
  486.   
  487. 154         simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");         
  488.   
  489. 155         for (TestVo testVo : results) {    
  490.   
  491. 156             System.out.println(testVo.getName() + "\t" + testVo.getSex() + "\t" + simpleDateFormat.format(testVo.getBrith()));    
  492.   
  493. 157         }    
  494.   
  495. 158     }    
  496.   
  497. 159 }   
  498. 1 ExcelExport.java;   
  499. 001 package cn.chn.chen.dev.excel;    
  500.   
  501. 002      
  502.   
  503. 003 import java.io.File;    
  504.   
  505. 004 import java.io.FileOutputStream;    
  506.   
  507. 005 import java.io.IOException;    
  508.   
  509. 006 import java.io.OutputStream;    
  510.   
  511. 007 import java.lang.reflect.Field;    
  512.   
  513. 008 import java.lang.reflect.Method;    
  514.   
  515. 009 import java.text.SimpleDateFormat;    
  516.   
  517. 010 import java.util.ArrayList;    
  518.   
  519. 011 import java.util.Collection;    
  520.   
  521. 012 import java.util.Date;    
  522.   
  523. 013 import java.util.Iterator;    
  524.   
  525. 014 import java.util.List;    
  526.   
  527. 015      
  528.   
  529. 016 import org.apache.poi.hssf.usermodel.HSSFCell;    
  530.   
  531. 017 import org.apache.poi.hssf.usermodel.HSSFCellStyle;    
  532.   
  533. 018 import org.apache.poi.hssf.usermodel.HSSFRichTextString;    
  534.   
  535. 019 import org.apache.poi.hssf.usermodel.HSSFRow;    
  536.   
  537. 020 import org.apache.poi.hssf.usermodel.HSSFSheet;    
  538.   
  539. 021 import org.apache.poi.hssf.usermodel.HSSFWorkbook;    
  540.   
  541. 022      
  542.   
  543. 023 /**   
  544.  
  545. 024  * <p>   
  546.  
  547. 025  * ExcelExport类主要用于-excel导出(POI).   
  548.  
  549. 026  * </p>   
  550.  
  551. 027  * <p>   
  552.  
  553. 028  * 创建时间 2011-4-21 - 下午12:34:33   
  554.  
  555. 029  * </p>   
  556.  
  557. 030  * @author IT山人   
  558.  
  559. 031  */   
  560.   
  561. 032 public class ExcelExport<T> {    
  562.   
  563. 033          
  564.   
  565. 034     //格式化日期        
  566.   
  567. 035     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
  568.   
  569. 036      
  570.   
  571. 037     /**   
  572.  
  573. 038      * <p>   
  574.  
  575. 039      * exportExcel方法-poi Excel导出.   
  576.  
  577. 040      * </p>   
  578.  
  579. 041      * <p>   
  580.  
  581. 042      * 创建人 IT山人 创建时间 2011-4-21 - 下午09:36:21   
  582.  
  583. 043      * </p>   
  584.  
  585. 044      * @param title 工作簿名称   
  586.  
  587. 045      * @param dataset 导出的数据集   
  588.  
  589. 046      * @param out 输出流   
  590.  
  591. 047      */   
  592.   
  593. 048     @SuppressWarnings("unchecked")    
  594.   
  595. 049     public void exportExcel(String title, Collection<T> dataset, OutputStream out) {    
  596.   
  597. 050         // 声明一个工作薄       
  598.   
  599. 051         try {    
  600.   
  601. 052             //首先检查数据看是否是正确的        
  602.   
  603. 053             Iterator<T> iterator = dataset.iterator();    
  604.   
  605. 054             if (dataset == null || !iterator.hasNext() || title == null || out == null) {    
  606.   
  607. 055                 throw new Exception("传入的数据不对!");    
  608.   
  609. 056             }    
  610.   
  611. 057             //取得实际泛型类        
  612.   
  613. 058             T tObject = iterator.next();    
  614.   
  615. 059             Class<T> clazz = (Class<T>) tObject.getClass();    
  616.   
  617. 060      
  618.   
  619. 061             HSSFWorkbook workbook = new HSSFWorkbook();    
  620.   
  621. 062             // 生成一个表格        
  622.   
  623. 063             HSSFSheet sheet = workbook.createSheet(title);    
  624.   
  625. 064             // 设置表格默认列宽度为20个字节        
  626.   
  627. 065             sheet.setDefaultColumnWidth(20);    
  628.   
  629. 066             // 生成一个样式        
  630.   
  631. 067             HSSFCellStyle style = workbook.createCellStyle();    
  632.   
  633. 068             // 设置标题样式        
  634.   
  635. 069             style = ExcelStyle.setHeadStyle(workbook, style);    
  636.   
  637. 070             // 得到所有字段        
  638.   
  639. 071             Field filed[] = tObject.getClass().getDeclaredFields();    
  640.   
  641. 072      
  642.   
  643. 073             // 标题        
  644.   
  645. 074             List<String> exportfieldtile = new ArrayList<String>();    
  646.   
  647. 075             // 导出的字段的get方法        
  648.   
  649. 076             List<Method> methodObj = new ArrayList<Method>();    
  650.   
  651. 077             // 遍历整个filed        
  652.   
  653. 078             for (int i = 0; i < filed.length; i++) {    
  654.   
  655. 079                 Field field = filed[i];    
  656.   
  657. 080                 ExcelAnnotation excelAnnotation = field.getAnnotation(ExcelAnnotation.class);    
  658.   
  659. 081                 // 如果设置了annottion        
  660.   
  661. 082                 if (excelAnnotation != null) {    
  662.   
  663. 083                     String exprot = excelAnnotation.exportName();    
  664.   
  665. 084                     // 添加到标题        
  666.   
  667. 085                     exportfieldtile.add(exprot);    
  668.   
  669. 086                     // 添加到需要导出的字段的方法        
  670.   
  671. 087                     String fieldname = field.getName();    
  672.   
  673. 088                     String getMethodName = "get" + fieldname.substring(01).toUpperCase() + fieldname.substring(1);    
  674.   
  675. 089                     Method getMethod = clazz.getMethod(getMethodName, new Class[] {});    
  676.   
  677. 090                     methodObj.add(getMethod);    
  678.   
  679. 091                 }    
  680.   
  681. 092             }    
  682.   
  683. 093      
  684.   
  685. 094             // 产生表格标题行        
  686.   
  687. 095             HSSFRow row = sheet.createRow(0);    
  688.   
  689. 096             for (int i = 0; i < exportfieldtile.size(); i++) {    
  690.   
  691. 097                 HSSFCell cell = row.createCell(i);    
  692.   
  693. 098                 cell.setCellStyle(style);    
  694.   
  695. 099                 HSSFRichTextString text = new HSSFRichTextString(exportfieldtile.get(i));    
  696.   
  697. 100                 cell.setCellValue(text);    
  698.   
  699. 101             }    
  700.   
  701. 102                  
  702.   
  703. 103             // 循环整个集合        
  704.   
  705. 104             int index = 0;    
  706.   
  707. 105             iterator = dataset.iterator();    
  708.   
  709. 106             while (iterator.hasNext()) {    
  710.   
  711. 107                 //从第二行开始写,第一行是标题        
  712.   
  713. 108                 index++;    
  714.   
  715. 109                 row = sheet.createRow(index);    
  716.   
  717. 110                 T t = (T) iterator.next();    
  718.   
  719. 111                 for (int k = 0; k < methodObj.size(); k++) {    
  720.   
  721. 112                     HSSFCell cell = row.createCell(k);    
  722.   
  723. 113                     Method getMethod = methodObj.get(k);    
  724.   
  725. 114                     Object value = getMethod.invoke(t, new Object[] {});    
  726.   
  727. 115                     String textValue = getValue(value);    
  728.   
  729. 116                     cell.setCellValue(textValue);    
  730.   
  731. 117                 }    
  732.   
  733. 118             }    
  734.   
  735. 119             workbook.write(out);    
  736.   
  737. 120         } catch (Exception e) {    
  738.   
  739. 121             e.printStackTrace();    
  740.   
  741. 122         }    
  742.   
  743. 123     }    
  744.   
  745. 124      
  746.   
  747. 125     /**   
  748.  
  749. 126      * <p>   
  750.  
  751. 127      * getValue方法-cell值处理.   
  752.  
  753. 128      * </p>   
  754.  
  755. 129      * <p>   
  756.  
  757. 130      * 创建人 IT山人 创建时间 2011-4-21 - 下午09:38:31   
  758.  
  759. 131      * </p>   
  760.  
  761. 132      * @param value   
  762.  
  763. 133      * @return   
  764.  
  765. 134      */   
  766.   
  767. 135     public String getValue(Object value) {    
  768.   
  769. 136         String textValue = "";    
  770.   
  771. 137         if (value == null) {    
  772.   
  773. 138             return textValue;    
  774.   
  775. 139         }    
  776.   
  777. 140         if (value instanceof Boolean) {    
  778.   
  779. 141             boolean bValue = (Boolean) value;    
  780.   
  781. 142             textValue = "是";    
  782.   
  783. 143             if (!bValue) {    
  784.   
  785. 144                 textValue = "否";    
  786.   
  787. 145             }    
  788.   
  789. 146         } else if (value instanceof Date) {    
  790.   
  791. 147             Date date = (Date) value;    
  792.   
  793. 148             textValue = sdf.format(date);    
  794.   
  795. 149      
  796.   
  797. 150         } else {    
  798.   
  799. 151             textValue = value.toString();    
  800.   
  801. 152         }    
  802.   
  803. 153         return textValue;    
  804.   
  805. 154     }       
  806.   
  807. 155      
  808.   
  809. 156     public static void main(String[] args) throws IOException {    
  810.   
  811. 157         OutputStream out = new FileOutputStream("D:\\testOne1.xls");    
  812.   
  813. 158         ExcelExport<TestVo> ex = new ExcelExport<TestVo>();    
  814.   
  815. 159         ImportExcel<TestVo> test = new ImportExcel<TestVo>(TestVo.class);    
  816.   
  817. 160         File file = new File("D:\\testOne.xls");    
  818.   
  819. 161         List<TestVo> results = (List<TestVo>) test.importExcel(file);    
  820.   
  821. 162      
  822.   
  823. 163         ex.exportExcel("测试", results, out);    
  824.   
  825. 164         out.close();    
  826.   
  827. 165     }    
  828.   
  829. 166 }   
  830. 1 ImportExcell.java;   
  831. 001 package cn.chn.chen.dev.excel;    
  832.   
  833. 002      
  834.   
  835. 003 import java.io.File;    
  836.   
  837. 004 import java.io.FileInputStream;    
  838.   
  839. 005 import java.io.FileNotFoundException;    
  840.   
  841. 006 import java.io.IOException;    
  842.   
  843. 007 import java.text.DecimalFormat;    
  844.   
  845. 008 import java.text.NumberFormat;    
  846.   
  847. 009 import java.util.ArrayList;    
  848.   
  849. 010 import java.util.HashMap;    
  850.   
  851. 011 import java.util.Iterator;    
  852.   
  853. 012 import java.util.List;    
  854.   
  855. 013 import java.util.Map;    
  856.   
  857. 014      
  858.   
  859. 015 import org.apache.commons.lang.StringUtils;    
  860.   
  861. 016 import org.apache.commons.logging.Log;    
  862.   
  863. 017 import org.apache.commons.logging.LogFactory;    
  864.   
  865. 018 import org.apache.poi.hssf.usermodel.HSSFCell;    
  866.   
  867. 019 import org.apache.poi.hssf.usermodel.HSSFDateUtil;    
  868.   
  869. 020 import org.apache.poi.hssf.usermodel.HSSFSheet;    
  870.   
  871. 021 import org.apache.poi.hssf.usermodel.HSSFWorkbook;    
  872.   
  873. 022 import org.apache.poi.ss.usermodel.Cell;    
  874.   
  875. 023 import org.apache.poi.ss.usermodel.Row;    
  876.   
  877. 024      
  878.   
  879. 025 /**   
  880.  
  881. 026  * <p>   
  882.  
  883. 027  * ImportExcell类主要用于-.   
  884.  
  885. 028  * </p>   
  886.  
  887. 029  * <p>   
  888.  
  889. 030  * 创建时间 2011-4-21 - 下午04:45:33   
  890.  
  891. 031  * </p>   
  892.  
  893. 032  * @author IT山人   
  894.  
  895. 033  */   
  896.   
  897. 034 public class ImportExcell {    
  898.   
  899. 035     private static final Log log = LogFactory.getLog(ImportExcell.class);    
  900.   
  901. 036     /**   
  902.  
  903. 037      * <p>   
  904.  
  905. 038      * readExcel方法-读取excel,行为list,列为Map.   
  906.  
  907. 039      * </p>   
  908.  
  909. 040      * <p>   
  910.  
  911. 041      * 创建人 IT山人 创建时间 2011-4-21 - 下午09:46:33   
  912.  
  913. 042      * </p>   
  914.  
  915. 043      * @param file excel文件   
  916.  
  917. 044      * @return excel表数据集合-行为list,列为Map   
  918.  
  919. 045      */   
  920.   
  921. 046     public List<Map<String, String>> readExcel(File file) {    
  922.   
  923. 047         log.info("读取excel开始...");    
  924.   
  925. 048         List<Map<String, String>> dataset = new ArrayList<Map<String, String>>();    
  926.   
  927. 049              
  928.   
  929. 050         try {    
  930.   
  931. 051             // 将传入的File构造为FileInputStream;     
  932.   
  933. 052             FileInputStream inputStream = new FileInputStream(file);    
  934.   
  935. 053             // 得到工作表     
  936.   
  937. 054             HSSFWorkbook book  = new HSSFWorkbook(inputStream);    
  938.   
  939. 055             // 得到第一页     
  940.   
  941. 056             HSSFSheet sheet = book.getSheetAt(0);    
  942.   
  943. 057             // 得到第一面的所有行     
  944.   
  945. 058             Iterator<Row> rowIterator = sheet.rowIterator();    
  946.   
  947. 059      
  948.   
  949. 060             // 得到第一行,也就是标题行     
  950.   
  951. 061             @SuppressWarnings("unused")    
  952.   
  953. 062             Row titleRow = rowIterator.next();    
  954.   
  955. 063                  
  956.   
  957. 064             while (rowIterator.hasNext()) {    
  958.   
  959. 065                 Row row = rowIterator.next();    
  960.   
  961. 066                 Map<String, String> map = this.creatObjectByRow(row);    
  962.   
  963. 067                 dataset.add(map);    
  964.   
  965. 068             }    
  966.   
  967. 069         } catch (FileNotFoundException e1) {    
  968.   
  969. 070             // TODO Auto-generated catch block     
  970.   
  971. 071             e1.printStackTrace();    
  972.   
  973. 072         } catch (IOException e2) {    
  974.   
  975. 073             // TODO Auto-generated catch block     
  976.   
  977. 074             e2.printStackTrace();    
  978.   
  979. 075         } catch (Exception e) {    
  980.   
  981. 076             // TODO: handle exception     
  982.   
  983. 077         }    
  984.   
  985. 078         log.info("读取excel结束...");    
  986.   
  987. 079         return dataset;    
  988.   
  989. 080     }    
  990.   
  991. 081          
  992.   
  993. 082     /**   
  994.  
  995. 083      * <p>   
  996.  
  997. 084      * creatObjectByRow方法-将每行的数据装载Map中.   
  998.  
  999. 085      * </p>   
  1000.  
  1001. 086      * <p>   
  1002.  
  1003. 087      * 创建人 IT山人 创建时间 2011-4-21 - 下午09:48:17   
  1004.  
  1005. 088      * </p>   
  1006.  
  1007. 089      * @param row   
  1008.  
  1009. 090      * @return   
  1010.  
  1011. 091      */   
  1012.   
  1013. 092     private Map<String, String> creatObjectByRow(Row row) {    
  1014.   
  1015. 093         // 行的所有列     
  1016.   
  1017. 094         Iterator<Cell> cellBody = row.cellIterator();    
  1018.   
  1019. 095         // 遍历一行的列     
  1020.   
  1021. 096         int col = 1;    
  1022.   
  1023. 097         Map<String, String> map = new HashMap<String, String>();    
  1024.   
  1025. 098         while (cellBody.hasNext()) {    
  1026.   
  1027. 099             String field = String.valueOf(col++);    
  1028.   
  1029. 100             Cell cell = cellBody.next();    
  1030.   
  1031. 101             if (cell != null) {    
  1032.   
  1033. 102                 switch (cell.getCellType()) {    
  1034.   
  1035. 103                     case HSSFCell.CELL_TYPE_STRING:     // 字符     
  1036.   
  1037. 104                         map.put(field, StringUtils.trim(cell.getStringCellValue()));    
  1038.   
  1039. 105                         break;    
  1040.   
  1041. 106                     case HSSFCell.CELL_TYPE_BOOLEAN:    // 布尔     
  1042.   
  1043. 107                         map.put(field, StringUtils.trim(cell.getStringCellValue()));    
  1044.   
  1045. 108                         break;    
  1046.   
  1047. 109                     case HSSFCell.CELL_TYPE_NUMERIC:    // 数字     
  1048.   
  1049. 110                         if (HSSFDateUtil.isCellDateFormatted(cell)) {// 是否为日期格式     
  1050.   
  1051. 111                             map.put(field, String.valueOf(cell.getDateCellValue()));    
  1052.   
  1053. 112                         } else {    
  1054.   
  1055. 113                             Double cellValue_dob = cell.getNumericCellValue();// 读取cell内数据     
  1056.   
  1057. 114                             if (String.valueOf(cellValue_dob).length() > 11) { // 如果读取到的是手机号码,需要匹配数字格式     
  1058.   
  1059. 115                                 DecimalFormat format = (DecimalFormat) NumberFormat.getInstance();    
  1060.   
  1061. 116                                 //format.applyPattern("00000000000");     
  1062.   
  1063. 117                                 map.put(field, format.format(cellValue_dob));    
  1064.   
  1065. 118                             } else { // 如果读取到的是比较短的数字,则去掉尾数(.0)后显示     
  1066.   
  1067. 119                                 map.put(field, cellValue_dob.toString().substring(0, cellValue_dob.toString().length() - 2));    
  1068.   
  1069. 120                             }    
  1070.   
  1071. 121                         }    
  1072.   
  1073. 122                         break;    
  1074.   
  1075. 123                     case HSSFCell.CELL_TYPE_FORMULA:    // 公式      
  1076.   
  1077. 124                         map.put(field, String.valueOf(cell.getNumericCellValue()));    
  1078.   
  1079. 125                         break;    
  1080.   
  1081. 126                     case HSSFCell.CELL_TYPE_BLANK:      // 空     
  1082.   
  1083. 127                         map.put(field, StringUtils.trim(cell.getStringCellValue()));    
  1084.   
  1085. 128                         break;    
  1086.   
  1087. 129                     case HSSFCell.CELL_TYPE_ERROR:      // 异常     
  1088.   
  1089. 130                         map.put(field, StringUtils.trim(cell.getStringCellValue()));    
  1090.   
  1091. 131                         break;    
  1092.   
  1093. 132                     default:    
  1094.   
  1095. 133                         map.put(field, StringUtils.trim(cell.getStringCellValue()));    
  1096.   
  1097. 134                         break;    
  1098.   
  1099. 135                 }    
  1100.   
  1101. 136             }    
  1102.   
  1103. 137         }    
  1104.   
  1105. 138         return map;    
  1106.   
  1107. 139     }    
  1108.   
  1109. 140      
  1110.   
  1111. 141     public static void main(String[] args) {    
  1112.   
  1113. 142         // TODO Auto-generated method stub     
  1114.   
  1115. 143         ImportExcell inport = new ImportExcell();    
  1116.   
  1117. 144         File file = new File("D:\\testOne.xls");    
  1118.   
  1119. 145         List<Map<String, String>> mapList = inport.readExcel(file);    
  1120.   
  1121. 146         for (Map<String, String> map : mapList) {    
  1122.   
  1123. 147 //          Iterator<Entry<String, String>> iterator = map.entrySet().iterator();     
  1124.   
  1125. 148 //          while (iterator.hasNext()) {     
  1126.   
  1127. 149 //              Map.Entry<String, String> entry = iterator.next();     
  1128.   
  1129. 150 //              String key = entry.getKey();     
  1130.   
  1131. 151 //              String value = entry.getValue();     
  1132.   
  1133. 152 //              System.out.println("key:" + key + "\tvalue:" + value);     
  1134.   
  1135. 153 //          }     
  1136.   
  1137. 154             TestVo t = new TestVo();    
  1138.   
  1139. 155             t.setName(map.get("1"));    
  1140.   
  1141. 156             System.out.println(t.getName());    
  1142.   
  1143. 157         }    
  1144.   
  1145. 158     }    
  1146.   
  1147. 159 }   
  1148. 1 TestVo.java;   
  1149. 01 public class TestVo {    
  1150.   
  1151. 02          
  1152.   
  1153. 03     @ExcelAnnotation(exportName="姓名")    
  1154.   
  1155. 04     private String name;    
  1156.   
  1157. 05          
  1158.   
  1159. 06     @ExcelAnnotation(exportName="性别")    
  1160.   
  1161. 07     private Integer sex;    
  1162.   
  1163. 08          
  1164.   
  1165. 09     @ExcelAnnotation(exportName="出生年月")    
  1166.   
  1167. 10     private Date brith;    
  1168.   
  1169. 11      
  1170.   
  1171. 12     /**   
  1172.  
  1173. 13      * @return 返回 name   
  1174.  
  1175. 14      */   
  1176.   
  1177. 15     public String getName() {    
  1178.   
  1179. 16         return name;    
  1180.   
  1181. 17     }    
  1182.   
  1183. 18      
  1184.   
  1185. 19     /**   
  1186.  
  1187. 20      * @param name 设置 name   
  1188.  
  1189. 21      */   
  1190.   
  1191. 22     public void setName(String name) {    
  1192.   
  1193. 23         this.name = name;    
  1194.   
  1195. 24     }    
  1196.   
  1197. 25      
  1198.   
  1199. 26     /**   
  1200.  
  1201. 27      * @return 返回 sex   
  1202.  
  1203. 28      */   
  1204.   
  1205. 29     public Integer getSex() {    
  1206.   
  1207. 30         return sex;    
  1208.   
  1209. 31     }    
  1210.   
  1211. 32      
  1212.   
  1213. 33     /**   
  1214.  
  1215. 34      * @param sex 设置 sex   
  1216.  
  1217. 35      */   
  1218.   
  1219. 36     public void setSex(Integer sex) {    
  1220.   
  1221. 37         this.sex = sex;    
  1222.   
  1223. 38     }    
  1224.   
  1225. 39      
  1226.   
  1227. 40     /**   
  1228.  
  1229. 41      * @return 返回 brith   
  1230.  
  1231. 42      */   
  1232.   
  1233. 43     public Date getBrith() {    
  1234.   
  1235. 44         return brith;    
  1236.   
  1237. 45     }    
  1238.   
  1239. 46      
  1240.   
  1241. 47     /**   
  1242.  
  1243. 48      * @param brith 设置 brith   
  1244.  
  1245. 49      */   
  1246.   
  1247. 50     public void setBrith(Date brith) {    
  1248.   
  1249. 51         this.brith = brith;    
  1250.   
  1251. 52     }    
  1252.   
  1253. 53          
  1254.   
  1255. 54 }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值