使用反射实现通用的POI导出Excel

来源:互联网 发布:android 珍藏源码 编辑:程序博客网 时间:2024/06/05 20:38

使用反射实现通用的POI导出Excel

整理出来的实用的工具类,使用POI实现数据导出到excel,平时导出Excel都是写死的,今天特意整理出来一篇通用的导出Excel方法。使用的Java反射机制
可直接复制粘贴使用
POI所需jar包下载地址:点我下载
代码如下

/**     * 使用poi通过反射导出Excel(通用方法)     *      * @param data     *            需要导出的数据     * @param saveFilePath     *            导出文件所在路径     * @return      * @return 成功返回true 失败返回false     * @throws Exception     */    public static <T> boolean generateSheet(List<T> data,            String saveFilePath) throws Exception {        HSSFWorkbook wb = new HSSFWorkbook();        HSSFSheet sheet = wb.createSheet("0"); // 获取到工作表        HSSFRow row = sheet.createRow(0); // 获取第一行(excel中的行默认从0开始,所以这就是为什么,一个excel必须有字段列头),即,字段列头,便于赋值        // System.out.println(sheet.getLastRowNum() + " " +        // row.getLastCellNum()); // 分别得到最后一行的行号,和一条记录的最后一个单元格        FileOutputStream out = new FileOutputStream(saveFilePath); // 向d://test.xls中写数据        // 遍历集合数据,产生数据行        Iterator<T> it = data.iterator();        int index = 0;        boolean flag = true;        try {            while (it.hasNext()) {                row = sheet.createRow(index++);//若不是在已有Excel表格后面追加数据 则使用该条语句                // 创建单元格,并设置值                T t = (T) it.next();                // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值                Field[] fields = t.getClass().getDeclaredFields();                for (short i = 0; i < fields.length; i++) {                    Field field = fields[i];                    if (field.toString().contains("static")) {                        continue;                    }                    HSSFCell cell = row.createCell((short) i);                    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 instanceof Date) {                        Date date = (Date) value;                        SimpleDateFormat sdf = new SimpleDateFormat(                                "yyyy-mm-dd");                        textValue = sdf.format(date);                    } else {                        // 其它数据类型都当作字符串简单处理                        if (value == null) {                            value = "";                        }                        textValue = value.toString();                    }                    if (textValue != null) {                        Pattern p = Pattern.compile("^//d+(//.//d+)?{1}quot;");                        Matcher matcher = p.matcher(textValue);                        if (matcher.matches()) {                            // 是数字当作double处理                            cell.setCellValue(Double.parseDouble(textValue));                        } else {                            cell.setCellValue(textValue);                        }                    }                }            }        } catch (Exception e) {            flag = false;            e.printStackTrace();        } finally {            out.flush();            wb.write(out);            out.close();        }        System.out.println("导出完毕");        return flag;    }

测试方法如下:
其中Emp实体类为Oracle数据库中自带Emp表中的字段,这里便不再列举

public static void main(String[] args) {        List empList = new ArrayList<>();        Emp e = new Emp(101, "小a", "经理", 1234, new Date(), 3200.0, 100.0, 20);        Emp e1 = new Emp(102, "小b", "销售", 1234, new Date(), 3210.0, 100.0, 20);        Emp e2 = new Emp(103, "小c", "测试", 1234, new Date(), 3220.0, 0.0, 20);        Emp e3 = new Emp(104, "小d", "开发", 1234, new Date(), 3250.0, 0.0, 20);        Emp e4 = new Emp(105, "小e", "实施", 1234, new Date(), 3600.0, 0.0, 20);        empList.add(e);        empList.add(e1);        empList.add(e2);        empList.add(e3);        empList.add(e4);        try {            ExportExcelUtil2.generateSheet(empList,  "d://test.xls");        } catch (Exception e5) {            e5.printStackTrace();        }    }
0 0
原创粉丝点击