通过模板生成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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • phpstudy本地搭建域名访问

    phpstudy本地搭建域名访问

    2021年10月9日
    37
  • java版我的世界_我的世界Java版1.16[通俗易懂]

    java版我的世界_我的世界Java版1.16[通俗易懂]我的世界Java版1.16是我的世界的特殊版本,这个版本的我的世界深受玩家们的喜欢,小编为各位玩家带来了最新的我的世界Java版1.16手机版本,不仅游戏内容在一定程度上丰富十足,画面打造也非常的精美,玩过的小伙伴都赞不绝口,喜欢的玩家就来下载吧!我的世界Java版1.16游戏说明JAVA版JAVA版应该算是玩家接触到的最广的版本,也是游戏内容最丰富的版本。事实上,JAVA版本就是PC版,是我的世…

    2022年7月7日
    60
  • python 元类编程_python定义元组

    python 元类编程_python定义元组前言通常我们创建类都是使用class类名,但是小伙伴们有没有想过,类是由谁来创建的呢,python中常说的万物皆对象,对象是由类创建的,那类本身也可以看做是对象,类可以由元类type创建type

    2022年7月30日
    4
  • 开启新征程[通俗易懂]

    开启新征程[通俗易懂]开启新征程

    2022年4月22日
    40
  • DayDayUp:2020,再见了,不平凡的一年,让我懂得了珍惜,让我明白了越努力越幸运[通俗易懂]

    DayDayUp:2020,再见了,不平凡的一年,让我懂得了珍惜,让我明白了越努力越幸运[通俗易懂]DayDayUp:2020,再见了,不平凡的一年,让我懂得了珍惜,让我明白了越努力越幸运导读:2020年的开篇,开的太意外,无论以什么样的眼光去回顾2020,它一定是载入史册的一年。突然起来的疫情,打得人们措手不及!人生的确不易,每个人都在负重前行,致敬那些可爱的人,感谢钟院士,感谢医护人员,感谢我们这这个强大的国家。2020年,太特殊,特殊的就像一场梦,无数的关键词涌入了记忆的心头:新冠,武汉,没毕业照,科比……前几天看到这样的一段话:2020年,最大的收获是一身伤,一身债,半条命、还活.

    2022年7月26日
    5
  • SLAM算法解析[通俗易懂]

    SLAM算法解析[通俗易懂]【嵌牛导读】:SLAM(SimultaneousLocalizationandMapping)是业界公认视觉领域空间定位技术的前沿方向,中文译名为「同步定位与地图构建」,它主要用于解决机器人在未知环境运动时的定位和地图构建问题。【嵌牛鼻子】:有人就曾打比方,若是手机离开了WIFI和数据网络,就像无人车和机器人,离开了SLAM一样。【嵌牛正文】:目前科技发展速度飞快,想让用户在AR/VR、机器人、无人机、无人驾驶领域体验加强,还是需要更多前沿技术做支持,SLAM就是其中之一。实际上

    2022年6月29日
    42

发表回复

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

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