通过模板生成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)
上一篇 2022年7月24日 下午12:36
下一篇 2022年7月24日 下午12:36


相关推荐

  • M1芯片Mac 安装git

    M1芯片Mac 安装gitM1 芯片 Mac 安装 git 本文 git 安装是使用了 mac 下的包管理工具 homebrew 如果你还没有安装 那真是太不应该了 作为一个开发人员 首先你要安装 homebrew 因为它实在是太方便了 homebrew 安装教程 M1 芯片 MacHomebrew 安装直接使用 homebrew 安装即可 brewinstallg 配置查看是否已配置 cd ssh 如果不能进入该目录 说明没生成过 检查下是否配置过 git 账户 gitconfiglis 重

    2026年3月18日
    2
  • 软件测试基础知识大全_软件测试主要学的内容有哪些

    软件测试基础知识大全_软件测试主要学的内容有哪些一、软件测试概述1、软件缺陷软件缺陷:又称之为“Bug”。即计算机软件或程序中存在的某种破坏正常运行能力的问题、错误,或者隐藏的功能缺陷。缺陷的表现形式:软件没有实现产品规格说明书所要求的功能模块;软件中出现了产品规格说明指明不应该出现的错误;软件实现了产品规格说明中没有提到的功能需求;软件没有实现虽然产品规格说明没有明确提及但应该实现的目标;软件难以理解、不易使用、运行缓慢、用户体验不友好;产生软件缺陷的原因:需求不清晰;系统结构较为复杂;对程序逻辑路径或者数据范围考虑不全面

    2026年4月15日
    16
  • 微信小程序使用MQTT.js连接阿里云IoT物联网平台[通俗易懂]

    微信小程序使用MQTT.js连接阿里云IoT物联网平台[通俗易懂]前言最近公司要做物联网控制,觉得写app不能够兼容Android和iOS,于是选定了微信小程序来作为控制端,为了能够实时的监听到设备的状态变化,需要服务器能够主动推消息给小程序,一开始考虑了websocket,由服务器进行上报的数据监听,小程序使用websocket连接服务器接收消息,虽然能实现,但是加上业务逻辑之后就太复杂终归不好(因为服务器也是自己写–泪奔)于是想着,websocket既然…………………

    2022年8月31日
    14
  • 做网站-mysql表字段设计

    做网站-mysql表字段设计

    2021年10月31日
    39
  • position属性值有哪些_静态web和动态web的区别

    position属性值有哪些_静态web和动态web的区别1:static静态定位,是默认值,当代码使用top,left.等,无效2:absolute绝对定位,相对于父元素进行定位,元素通过top,right,left等进行定位3:fixed

    2022年8月1日
    7
  • scrapy安装步骤_scrapy官网

    scrapy安装步骤_scrapy官网安装scrapy过程中出现各种包安装错误,所以自己一直看教程知道scrapy安装需要准备好各种环境。这些包按照从下到上的顺序下载,lxml这个包按下文教程安装。不想看过多文字和图片的懒人们可看教程视频:http://www.iqiyi.com/w_19rz36pjft.html利用pipinstall命令安装pywin32,pyopenssl.这两个包可在cmd安装成功pip…

    2026年1月17日
    4

发表回复

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

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