通过模板生成Excel表格——XLSTransformer

通过模板生成Excel表格——XLSTransformer/***根据模版生成保存到指定位置*@parampathTemplateFileName*@paramlist*@parampathResultFileName*@return*/publicstaticbooleancreateExcel(StringpathTemplateFileNam…

大家好,又见面了,我是你们的朋友全栈君。

依赖:

		<dependency>
            <groupId>net.sf.jxls</groupId>
            <artifactId>jxls-core</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>net.sf.jxls</groupId>
            <artifactId>jxls-reader</artifactId>
            <version>1.0</version>
        </dependency>
	/** * 根据模版生成保存到指定位置 * @param pathTemplateFileName 模版路径 * @param list * @param pathResultFileName 存放路径 * @return */
    public static boolean createExcel(String pathTemplateFileName, List<?> list, String pathResultFileName){ 
   
        //创建XLSTransformer对象
        XLSTransformer transformer = new XLSTransformer();
        //获取java项目编译后根路径
        //URL url = ExcelUtil.class.getClassLoader().getResource("");
        //得到模板文件路径
        //String srcFilePath = url.getPath() + templateFileName;
        //String destFilePath = url.getPath() + resultFileName;
        Map<String,Object> beanParams = new HashMap<String,Object>();
        beanParams.put("list", list);
        try { 
   
            //生成Excel文件
            transformer.transformXLS(pathTemplateFileName, beanParams,pathResultFileName );
            return true;
        } catch (Exception e) { 
   
            e.printStackTrace();
            return false;
        }

    }

    /** * 根据模版生成 excel的工作簿 * @param pathTemplateFileName * @param list * @return */
    public static Workbook createHSSFWorkbook(String pathTemplateFileName, List<?> list){ 
   
        //创建XLSTransformer对象
        XLSTransformer transformer = new XLSTransformer();

        Map<String,Object> beanParams = new HashMap<String,Object>();
        beanParams.put("list", list);
        Workbook hssfWorkbook=null;
        try { 
   
            InputStream is = new BufferedInputStream(new FileInputStream(pathTemplateFileName));
            hssfWorkbook = transformer.transformXLS(is, beanParams);
            is. close();
        } catch (Exception e) { 
   
            e.printStackTrace();

        }
        return hssfWorkbook;
    }


    /** * 写到输入流中 * @param pathTemplateFileName * @param list */
    public static InputStream getExceInput(String pathTemplateFileName, List<?> list) throws Exception { 
   
        XLSTransformer transformer = new XLSTransformer();
        Map<String,Object> beanParams = new HashMap<String,Object>();
        beanParams.put("dateFormat",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        beanParams.put("list", list);
        InputStream inputStream = new BufferedInputStream(new FileInputStream(pathTemplateFileName));
        transformer.transformXLS(inputStream, beanParams);
        return inputStream;
    }
    public static boolean setExceOutput(String pathTemplateFileName, List<?> list,OutputStream outputStream){ 
   

        XLSTransformer transformer = new XLSTransformer();
        Map<String,Object> beanParams = new HashMap<String,Object>();
        InputStream is=null;
        try { 
   
            beanParams.put("list", list);
            is = new BufferedInputStream(new FileInputStream(pathTemplateFileName));
            Workbook wb = transformer.transformXLS(is, beanParams);
            wb.write(outputStream);
            return true;
        }catch (ParsePropertyException ex){ 
   
            ex.printStackTrace();
        }catch (InvalidFormatException ex){ 
   
            ex.printStackTrace();
        }catch (IOException ex){ 
   
            ex.printStackTrace();
        } finally { 
   
            if (is!=null){ 
   
                try { 
   
                    is.close();
                } catch (IOException e) { 
   
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
    /** * 装配 返回数据流水 * @param pathTemplateFileName * @param list * @return */
    public static   byte[] getExceByte(String pathTemplateFileName, List<?> list){ 
   
        //创建XLSTransformer对象
        XLSTransformer transformer = new XLSTransformer();
        Map<String,Object> beanParams = new HashMap<String,Object>();
        beanParams.put("list", list);
        byte[] bytes=null;
        InputStream is=null;
        ByteArrayOutputStream out=null;
        try { 
   
            is = new BufferedInputStream(new FileInputStream(pathTemplateFileName));
            Workbook wb = transformer.transformXLS(is, beanParams);
            out = new ByteArrayOutputStream();
            wb.write(out);
            bytes = out.toByteArray();
        } catch (Exception e) { 
   
            e.printStackTrace();
        }finally { 
   
            try { 
   
                if (is!=null) { 
   
                    is.close();
                }
            } catch (IOException e) { 
   
                e.printStackTrace();
            }
            try { 
   
                if (out!=null) { 
   
                    out.close();
                }
            } catch (IOException e) { 
   
                e.printStackTrace();
            }
        }
        return bytes;
    }

    /** *根据工作博导出集合对象 * @param wb * @param sheetAt 解析那个sheet页 * @param statIndex 那一行开始 * @param tClass 解析目标对象 * @param <T> * @return * @throws IllegalAccessException * @throws InstantiationException */
    public static <T> List<T> getList(Workbook wb,int sheetAt,int statIndex,Class<T> tClass ) throws IllegalAccessException, InstantiationException { 
   
        List<T> list=new ArrayList<>();
        Sheet sheet = wb.getSheetAt(sheetAt);
        int lastRowNum = sheet.getLastRowNum();
        for (int i=statIndex;i<=lastRowNum;i++){ 
   
            Row row = sheet.getRow(i);
            if(row==null){ 
   
                continue;
            }
            T t= tClass.newInstance();
            Field[] declaredFields = tClass.getDeclaredFields();
            for (Field f : declaredFields) { 
   
                f.setAccessible(true); //设置些属性是可以访问的
                //Object val = f.get(t);//得到此属性的值
                //String name = f.getName();//获得属性名
                ExcelIndex annotation = f.getAnnotation(ExcelIndex.class);
                if (annotation==null){ 
   
                    continue;
                }
                Cell cell = row.getCell(annotation.value());
                f.set(t,getFCellValue(cell));
            }
            list.add(t);
        }
        return list;
    }


    /** * 获取单元格的值 * @param cell * @return */
    private static   Object getFCellValue(Cell cell){ 
   
        if(cell==null){ 
   
            return null;
        }
        switch (cell.getCellType()) { 
   
            case 0: // 数字
                return cell.getNumericCellValue();
            case 1: // 字符串
                return cell.getStringCellValue();
            case 4: // Boolean
                return cell.getBooleanCellValue();
            case 2: // 公式
                return    cell.getCellFormula();
            case 3: // 空值
                return null;
            case 5: // 故障
                return null;
            default://未知
                return null;
        }
    }

    public static void main(String[] args) throws Throwable { 
   


        createExcel("D:/555.xlsx",new ArrayList<>(),"D:/test.xlsx");

    }




版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/163867.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Git创建远程分支并提交代码到远程分支

    Git创建远程分支并提交代码到远程分支1、可以通过gitbranch-r命令查看远端库的分支情况如图所示,远程仓库只有一个master分支2、从已有的分支创建新的分支(如从master分支),创建一个dev分支但此时并没有在远程仓库上创建分支如图所示还是只有一个master分支3、建立本地到远端仓库的链接–这样代码才能提交上去使用命令行gitpush–set-…

    2022年6月30日
    38
  • 安装下载App_windows server 2022下载

    安装下载App_windows server 2022下载安装指南入门标题页3WindowsServerAppFabric安装和配置指南3版权3版权所有3简介3清单:规划安装4硬件要求4使计算机作好安装准备5本节内容5安装关键的Windows更新5安装Windows更新6安装修补程序6KB9804236安装.NETFramework6安装W…

    2022年10月17日
    3
  • 递归和迭代的比较

    递归和迭代的比较迭代(Iteration)与递归(Recursion)是开发过程中常用的编程技巧,二者有相似,也有区别。1、递归简单地说,就是函数调用函数自己。通常把相同规则的业务,定义为一个函数,通过函数的重复调用,完成整体业务的实现。用有限的语句来定义对象的无限集合。比如,一个数字的阶乘计算,通过递归实现如下://递归publicstaticintrecursio…

    2022年6月5日
    49
  • js 洗牌算法_数据库洗牌算法

    js 洗牌算法_数据库洗牌算法概念洗牌算法即是把一组数组里的元素随机组合生成一个新数组。实现constshuffle=([…arr])=>{letm=arr.length;while(m){consti=Math.floor(Math.random()*m–);[arr[m],arr[i]]=[arr[i],arr[m]];}returnarr;};//测试consttes

    2022年9月21日
    5
  • jdbc 中 excute executeUpdate的用法作用

    jdbc 中 excute executeUpdate的用法作用Statement接口提供了三种执行SQL语句的方法:executeQuery、executeUpdate和execute。使用哪一个方法由SQL语句所产生的内容决定。 方法e

    2022年7月2日
    26
  • vue双向绑定经典案例「建议收藏」

    vue双向绑定经典案例「建议收藏」1、无需废话,直接上代码复制到新建的记事本文件,保存问demo.html即可。<scriptsrc=”https://cdn.staticfile.org/vue/2.2.2/vue.min.js”></script><!DOCTYPEhtml><html><head><metacharset=”utf-8″><title>欢迎系统</title></head>

    2025年11月17日
    7

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号