使用poi导入导出Excel(实测有效)

 1. 导入Excel将数据转换为对象:

/**
     * 传入一Excel表格,创建出对应的类集合 要求:类的字段名必须和Excel的首行的标题相同
     *
     * @param filePath
     * @param cls
     * @return
     * @throws InvalidFormatException
     * @throws IOException
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     */
    public static <T> List<T> readExcel(String filePath, Class<T> cls) throws InvalidFormatException, IOException,
            InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException,
            NoSuchFieldException, IllegalArgumentException, InvocationTargetException {
        File excelFile = new File(filePath);
        // 文件流
        ZipSecureFile.setMinInflateRatio(-1.0d);
        FileInputStream is = new FileInputStream(excelFile);
        // 这种方式完美支持Excel、2003/2007/2010
        Workbook workbook = WorkbookFactory.create(is);
        // 获取工作区(只提取第一个工作区)
        Sheet sheet = workbook.getSheetAt(0);
        // 文件的总行数
        int rowCount = sheet.getPhysicalNumberOfRows();
        // 对象的集合
        List<T> objList = new ArrayList<>();
        // 获得首行表示,单元格的内容必须与pojo类的字段名一致
        Row row1 = sheet.getRow(0);
        for (int i = 1; i < rowCount; i++) {
            // 解析每一行
            Row row = sheet.getRow(i);
            if (!isRowEmpty(row)) {
                // 反射创建对象
                T obj = cls.newInstance();
                for (int j = 0; j < row1.getPhysicalNumberOfCells(); j++) {
                    String title = row1.getCell(j).getStringCellValue();
                    String methodName = "set" + title.substring(0, 1).toUpperCase() + title.substring(1);
                    Cell cell = row.getCell(j);
                    if (cell != null) {
                        String value = null;
                        //这里可根据需要,增加对其它数据类型的判断
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                // 处理日期格式的数据
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                value = sdf.format(cell.getDateCellValue());
                            } else {
                                // 处理较长的数字格式的数据,防止数字过长,导致科学计数法
                                DecimalFormat df = new DecimalFormat("0");
                                value = df.format(cell.getNumericCellValue());
                            }
                        }
                        if (cell.getCellTypeEnum() == CellType.STRING) {
                            value = cell.getStringCellValue();
                        }
                        Method method = cls.getDeclaredMethod(methodName, cls.getDeclaredField(title).getType());
                        method.invoke(obj, value);
                    } else {
                        Method method = cls.getDeclaredMethod(methodName, cls.getDeclaredField(title).getType());
                        method.invoke(obj, 0);
                    }
                }
                objList.add(obj);
            }
        }
        return objList;
    }

    /**
     * 判断excel某行是否为空
     * @param row
     * @return
     */
    public static boolean isRowEmpty(Row row) {
        if (null == row) {
            return true;
        }
        //第一个列位置
        int firstCellNum = row.getFirstCellNum();
        //最后一列位置
        int lastCellNum = row.getLastCellNum();
        //空列数量
        int nullCellNum = 0;
        for (int c = firstCellNum; c < lastCellNum; c++) {
            Cell cell = row.getCell(c);
            if (null == cell || Cell.CELL_TYPE_BLANK == cell.getCellType()) {
                nullCellNum ++;
                continue;
            }
            cell.setCellType(Cell.CELL_TYPE_STRING);
            String cellValue = cell.getStringCellValue().trim();
            if (StringUtils.isEmpty(cellValue)) {
                nullCellNum ++;
            }
        }
        return nullCellNum == (lastCellNum - firstCellNum);
    }

方法调用:

// 读取user.xlsx中的账号信息,并解析成员工账号数据
String userPath =ResourceUtils.getURL("classpath:../excel/acl_user.xlsx").getPath();
List<UserVO> userInfos = ExcelReader.readExcel(userPath, UserVO.class);

2.将内存中的对象到出至Excel:

/**
     * 通用方法,导出excel
     * @param title 表格标题名
     * @param dataset 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。
     * @param out 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
     */
    public static <T> void exportExcel(String title, List<T> dataset, OutputStream out, String pattern)
            throws Exception {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);


        if (dataset == null || dataset.size() == 0){
            return;
        }

        T tempT = dataset.get(0);
        Field[] heads = tempT.getClass().getDeclaredFields();
        List<String> headList = new ArrayList<>();
        // 获取字段注解的表头
        for (int i = 0; i < heads.length; i++) {
            String name = heads[i].getName();
            headList.add(name);
        }
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headList.size(); i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headList.get(i));
            cell.setCellValue(text);

        }
        // 遍历集合数据,产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            Field[] fields = t.getClass().getDeclaredFields();
            List<Field> fieldsList = new ArrayList<>();
            for (Field field : fields) {
                fieldsList.add(field);
            }
            for (Field field : fieldsList) {
                HSSFCell cell = row.createCell(fieldsList.indexOf(field));
                String fieldName = field.getName();
                String getMethodName =
                        "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                Class tCls = t.getClass();
                Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
                Object value = getMethod.invoke(t, new Object[] {});
                // 判断值的类型后进行强制类型转换
                String textValue = null;
                if (value == null) {
                    cell.setCellValue("");
                }
                if (value instanceof Integer) {
                    int intValue = (Integer) value;
                    cell.setCellValue(intValue);
                } else if (value instanceof Float) {
                    float fValue = (Float) value;
                    cell.setCellValue(fValue);
                } else if (value instanceof Double) {
                    double dValue = (Double) value;
                    cell.setCellValue(dValue);
                } else if (value instanceof Long) {
                    long longValue = (Long) value;
                    cell.setCellValue(longValue);
                } else if (value instanceof Date) {
                    Date date = (Date) value;
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    textValue = sdf.format(date);
                    cell.setCellValue(textValue);
                } else {
                    // 其它数据类型都当作字符串简单处理
                    textValue = value == null ? "" : value.toString();
                    cell.setCellValue(textValue);
                }
            }
        }
        workbook.write(out);
    }

方法调用:

String userPath = ResourceUtils.getURL("classpath:excel/acl_user.xlsx").getPath();
        List<UserInfoVO> userInfos = ExcelReader.readExcel(userPath, UserInfoVO.class);
        System.out.println(userInfos);
        // 设置密码
        userInfos.forEach(user->{
            // 生成随机密码
            String pwd = PasswordUtil.generatePwd(8);
            user.setPwd(pwd);
        });
        System.out.println(userInfos);

        String title = "账号信息表";
        File file = new File(temp);
        if(!file.exists()){
            file.mkdirs();
        }
        //临时文件路径/文件名
        String downloadPath = file + "/employee.xls";
        OutputStream outputStream = new FileOutputStream(downloadPath);
        BaseExportExcel.exportExcel(title,userInfos,outputStream,"yyyy-MM-dd");

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值