阿里云服务器免费领卷啦。

捡代码论坛-最全的游戏源码下载技术网站!

 找回密码
 立 即 注 册

QQ登录

只需一步,快速开始

搜索
关于源码区的附件失效或欺骗帖, 处理办法
查看: 2364|回复: 0

导入Excel文件

[复制链接]

3

主题

10

回帖

106

积分

注册会员

Rank: 2

积分
106
发表于 2016-1-21 09:40:30 | 显示全部楼层 |阅读模式
  1. /**
  2. * 导入Excel文件(支持“XLS”和“XLSX”格式)
  3. * @author zw
  4. * @version 2015-03-10
  5. */
  6. public class ImportExcel {
  7.         
  8.         private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
  9.                         
  10.         /**
  11.          * 工作薄对象
  12.          */
  13.         private Workbook wb;
  14.         
  15.         /**
  16.          * 工作表对象
  17.          */
  18.         private Sheet sheet;
  19.         
  20.         /**
  21.          * 标题行号
  22.          */
  23.         private int headerNum;
  24.         
  25.         /**
  26.          * 构造函数
  27.          * @param path 导入文件,读取第一个工作表
  28.          * @param headerNum 标题行号,数据行号=标题行号+1
  29.          * @throws InvalidFormatException
  30.          * @throws IOException
  31.          */
  32.         public ImportExcel(String fileName, int headerNum)
  33.                         throws InvalidFormatException, IOException {
  34.                 this(new File(fileName), headerNum);
  35.         }
  36.         
  37.         /**
  38.          * 构造函数
  39.          * @param path 导入文件对象,读取第一个工作表
  40.          * @param headerNum 标题行号,数据行号=标题行号+1
  41.          * @throws InvalidFormatException
  42.          * @throws IOException
  43.          */
  44.         public ImportExcel(File file, int headerNum)
  45.                         throws InvalidFormatException, IOException {
  46.                 this(file, headerNum, 0);
  47.         }

  48.         /**
  49.          * 构造函数
  50.          * @param path 导入文件
  51.          * @param headerNum 标题行号,数据行号=标题行号+1
  52.          * @param sheetIndex 工作表编号
  53.          * @throws InvalidFormatException
  54.          * @throws IOException
  55.          */
  56.         public ImportExcel(String fileName, int headerNum, int sheetIndex)
  57.                         throws InvalidFormatException, IOException {
  58.                 this(new File(fileName), headerNum, sheetIndex);
  59.         }
  60.         
  61.         /**
  62.          * 构造函数
  63.          * @param path 导入文件对象
  64.          * @param headerNum 标题行号,数据行号=标题行号+1
  65.          * @param sheetIndex 工作表编号
  66.          * @throws InvalidFormatException
  67.          * @throws IOException
  68.          */
  69.         public ImportExcel(File file, int headerNum, int sheetIndex)
  70.                         throws InvalidFormatException, IOException {
  71.                 this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
  72.         }
  73.         
  74.         /**
  75.          * 构造函数
  76.          * @param file 导入文件对象
  77.          * @param headerNum 标题行号,数据行号=标题行号+1
  78.          * @param sheetIndex 工作表编号
  79.          * @throws InvalidFormatException
  80.          * @throws IOException
  81.          */
  82.         public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex)
  83.                         throws InvalidFormatException, IOException {
  84.                 this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
  85.         }

  86.         /**
  87.          * 构造函数
  88.          * @param path 导入文件对象
  89.          * @param headerNum 标题行号,数据行号=标题行号+1
  90.          * @param sheetIndex 工作表编号
  91.          * @throws InvalidFormatException
  92.          * @throws IOException
  93.          */
  94.         public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex)
  95.                         throws InvalidFormatException, IOException {
  96.                 if (StringUtils.isBlank(fileName)){
  97.                         throw new RuntimeException("导入文档为空!");
  98.                 }else if(fileName.toLowerCase().endsWith("xls")){   
  99.                         this.wb = new HSSFWorkbook(is);   
  100.         }else if(fileName.toLowerCase().endsWith("xlsx")){  
  101.                 this.wb = new XSSFWorkbook(is);
  102.         }else{  
  103.                 throw new RuntimeException("文档格式不正确!");
  104.         }  
  105.                 if (this.wb.getNumberOfSheets()<sheetIndex){
  106.                         throw new RuntimeException("文档中没有工作表!");
  107.                 }
  108.                 this.sheet = this.wb.getSheetAt(sheetIndex);
  109.                 this.headerNum = headerNum;
  110.                 log.debug("Initialize success.");
  111.         }
  112.         
  113.         /**
  114.          * 获取行对象
  115.          * @param rownum
  116.          * @return
  117.          */
  118.         public Row getRow(int rownum){
  119.                 return this.sheet.getRow(rownum);
  120.         }

  121.         /**
  122.          * 获取数据行号
  123.          * @return
  124.          */
  125.         public int getDataRowNum(){
  126.                 return headerNum+1;
  127.         }
  128.         
  129.         /**
  130.          * 获取最后一个数据行号
  131.          * @return
  132.          */
  133.         public int getLastDataRowNum(){
  134.                 return this.sheet.getLastRowNum()+headerNum;
  135.         }
  136.         
  137.         /**
  138.          * 获取最后一个列号
  139.          * @return
  140.          */
  141.         public int getLastCellNum(){
  142.                 return this.getRow(headerNum).getLastCellNum();
  143.         }
  144.         
  145.         /**
  146.          * 获取单元格值
  147.          * @param row 获取的行
  148.          * @param column 获取单元格列号
  149.          * @return 单元格值
  150.          */
  151.         public Object getCellValue(Row row, int column){
  152.                 Object val = "";
  153.                 try{
  154.                         Cell cell = row.getCell(column);
  155.                         if (cell != null){
  156.                                 if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
  157.                                         val = cell.getNumericCellValue();
  158.                                 }else if (cell.getCellType() == Cell.CELL_TYPE_STRING){
  159.                                         val = cell.getStringCellValue();
  160.                                 }else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA){
  161.                                         val = cell.getCellFormula();
  162.                                 }else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
  163.                                         val = cell.getBooleanCellValue();
  164.                                 }else if (cell.getCellType() == Cell.CELL_TYPE_ERROR){
  165.                                         val = cell.getErrorCellValue();
  166.                                 }
  167.                         }
  168.                 }catch (Exception e) {
  169.                         return val;
  170.                 }
  171.                 return val;
  172.         }
  173.         
  174.         /**
  175.          * 获取导入数据列表
  176.          * @param cls 导入对象类型
  177.          * @param groups 导入分组
  178.          */
  179.         public <E> List<E> getDataList(Class<E> cls, int... groups) throws InstantiationException, IllegalAccessException{
  180.                 List<Object[]> annotationList = Lists.newArrayList();
  181.                 // Get annotation field
  182.                 Field[] fs = cls.getDeclaredFields();
  183.                 for (Field f : fs){
  184.                         ExcelField ef = f.getAnnotation(ExcelField.class);
  185.                         if (ef != null && (ef.type()==0 || ef.type()==2)){
  186.                                 if (groups!=null && groups.length>0){
  187.                                         boolean inGroup = false;
  188.                                         for (int g : groups){
  189.                                                 if (inGroup){
  190.                                                         break;
  191.                                                 }
  192.                                                 for (int efg : ef.groups()){
  193.                                                         if (g == efg){
  194.                                                                 inGroup = true;
  195.                                                                 annotationList.add(new Object[]{ef, f});
  196.                                                                 break;
  197.                                                         }
  198.                                                 }
  199.                                         }
  200.                                 }else{
  201.                                         annotationList.add(new Object[]{ef, f});
  202.                                 }
  203.                         }
  204.                 }
  205.                 // Get annotation method
  206.                 Method[] ms = cls.getDeclaredMethods();
  207.                 for (Method m : ms){
  208.                         ExcelField ef = m.getAnnotation(ExcelField.class);
  209.                         if (ef != null && (ef.type()==0 || ef.type()==2)){
  210.                                 if (groups!=null && groups.length>0){
  211.                                         boolean inGroup = false;
  212.                                         for (int g : groups){
  213.                                                 if (inGroup){
  214.                                                         break;
  215.                                                 }
  216.                                                 for (int efg : ef.groups()){
  217.                                                         if (g == efg){
  218.                                                                 inGroup = true;
  219.                                                                 annotationList.add(new Object[]{ef, m});
  220.                                                                 break;
  221.                                                         }
  222.                                                 }
  223.                                         }
  224.                                 }else{
  225.                                         annotationList.add(new Object[]{ef, m});
  226.                                 }
  227.                         }
  228.                 }
  229.                 // Field sorting
  230.                 Collections.sort(annotationList, new Comparator<Object[]>() {
  231.                         public int compare(Object[] o1, Object[] o2) {
  232.                                 return new Integer(((ExcelField)o1[0]).sort()).compareTo(
  233.                                                 new Integer(((ExcelField)o2[0]).sort()));
  234.                         };
  235.                 });
  236.                 //log.debug("Import column count:"+annotationList.size());
  237.                 // Get excel data
  238.                 List<E> dataList = Lists.newArrayList();
  239.                 for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
  240.                         E e = (E)cls.newInstance();
  241.                         int column = 0;
  242.                         Row row = this.getRow(i);
  243.                         StringBuilder sb = new StringBuilder();
  244.                         for (Object[] os : annotationList){
  245.                                 Object val = this.getCellValue(row, column++);
  246.                                 if (val != null){
  247.                                         ExcelField ef = (ExcelField)os[0];
  248.                                         // If is dict type, get dict value
  249.                                         if (StringUtils.isNotBlank(ef.dictType())){
  250.                                                 val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
  251.                                                 //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
  252.                                         }
  253.                                         // Get param type and type cast
  254.                                         Class<?> valType = Class.class;
  255.                                         if (os[1] instanceof Field){
  256.                                                 valType = ((Field)os[1]).getType();
  257.                                         }else if (os[1] instanceof Method){
  258.                                                 Method method = ((Method)os[1]);
  259.                                                 if ("get".equals(method.getName().substring(0, 3))){
  260.                                                         valType = method.getReturnType();
  261.                                                 }else if("set".equals(method.getName().substring(0, 3))){
  262.                                                         valType = ((Method)os[1]).getParameterTypes()[0];
  263.                                                 }
  264.                                         }
  265.                                         //log.debug("Import value type: ["+i+","+column+"] " + valType);
  266.                                         try {
  267.                                                 if (valType == String.class){
  268.                                                         String s = String.valueOf(val.toString());
  269.                                                         if(StringUtils.endsWith(s, ".0")){
  270.                                                                 val = StringUtils.substringBefore(s, ".0");
  271.                                                         }else{
  272.                                                                 val = String.valueOf(val.toString());
  273.                                                         }
  274.                                                 }else if (valType == Integer.class){
  275.                                                         val = Double.valueOf(val.toString()).intValue();
  276.                                                 }else if (valType == Long.class){
  277.                                                         val = Double.valueOf(val.toString()).longValue();
  278.                                                 }else if (valType == Double.class){
  279.                                                         val = Double.valueOf(val.toString());
  280.                                                 }else if (valType == Float.class){
  281.                                                         val = Float.valueOf(val.toString());
  282.                                                 }else if (valType == Date.class){
  283.                                                         val = DateUtil.getJavaDate((Double)val);
  284.                                                 }else{
  285.                                                         if (ef.fieldType() != Class.class){
  286.                                                                 val = ef.fieldType().getMethod("getValue", String.class).invoke(null, val.toString());
  287.                                                         }else{
  288.                                                                 val = Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
  289.                                                                                 "fieldtype."+valType.getSimpleName()+"Type")).getMethod("getValue", String.class).invoke(null, val.toString());
  290.                                                         }
  291.                                                 }
  292.                                         } catch (Exception ex) {
  293.                                                 log.info("Get cell value ["+i+","+column+"] error: " + ex.toString());
  294.                                                 val = null;
  295.                                         }
  296.                                         // set entity value
  297.                                         if (os[1] instanceof Field){
  298.                                                 Reflections.invokeSetter(e, ((Field)os[1]).getName(), val);
  299.                                         }else if (os[1] instanceof Method){
  300.                                                 String mthodName = ((Method)os[1]).getName();
  301.                                                 if ("get".equals(mthodName.substring(0, 3))){
  302.                                                         mthodName = "set"+StringUtils.substringAfter(mthodName, "get");
  303.                                                 }
  304.                                                 Reflections.invokeMethod(e, mthodName, new Class[] {valType}, new Object[] {val});
  305.                                         }
  306.                                 }
  307.                                 sb.append(val+", ");
  308.                         }
  309.                         dataList.add(e);
  310.                         log.debug("Read success: ["+i+"] "+sb.toString());
  311.                 }
  312.                 return dataList;
  313.         }

  314. //        /**
  315. //         * 导入测试
  316. //         */
  317. //        public static void main(String[] args) throws Throwable {
  318. //               
  319. //                ImportExcel ei = new ImportExcel("target/export.xlsx", 1);
  320. //               
  321. //                for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {
  322. //                        Row row = ei.getRow(i);
  323. //                        for (int j = 0; j < ei.getLastCellNum(); j++) {
  324. //                                Object val = ei.getCellValue(row, j);
  325. //                                System.out.print(val+", ");
  326. //                        }
  327. //                        System.out.print("\n");
  328. //                }
  329. //               
  330. //        }

  331. }
复制代码


捡代码论坛-最全的游戏源码下载技术网站! - 论坛版权郑重声明:
1、本主题所有言论和图片纯属会员个人意见,与本论坛立场无关
2、本站所有主题由该帖子作者发表,该帖子作者与捡代码论坛-最全的游戏源码下载技术网站!享有帖子相关版权
3、捡代码论坛版权,详细了解请点击。
4、本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,不存在任何商业目的与商业用途。
5、若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。 我们不承担任何技术及版权问题,且不对任何资源负法律责任。
6、如无法链接失效或侵犯版权,请给我们来信:jiandaima@foxmail.com

回复

使用道具 举报

*滑块验证:
您需要登录后才可以回帖 登录 | 立 即 注 册

本版积分规则

技术支持
在线咨询
QQ咨询
3351529868

QQ|手机版|小黑屋|捡代码论坛-专业源码分享下载 ( 陕ICP备15015195号-1|网站地图

GMT+8, 2024-4-25 19:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表