POI导出的通用类,希望可以帮助到大家

public class POIUtil {

    private static HSSFCellStyle bodyStyle;

    private static HSSFFont bodyFont;

    private static HSSFCellStyle headStyle;

    private static HSSFFont headFont;

    /**
     * 导出Excel文件
     * 数据源的数据格式为List<Map<String K,String V>>
     *
     * @param objList  : Excel数据源
     * @param title    : 新建Sheet的名称
     * @param strTitle : Sheet各列的标题(第一行各列的名称)
     * @param strBody  : Sheet各列的取值方法名(各列的值在objClass中get方法名称)
     * @return
     */
    public static InputStream createExcel(List<Map<String, String>> objList, String title, String strTitle, String strBody) {
        // 创建工作簿(Excel文件)
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 创建Excel工作簿的第一个Sheet页
        HSSFSheet sheet = workbook.createSheet(title);

        // 创建Sheet页的文件头(第一行)
        createTitle(sheet, strTitle);

        // 创建Sheet页的文件体(后续行)
        String[] strArray = strBody.split(",");
        for (int objIndex = 0; objIndex < objList.size(); objIndex++) {
            Map map = objList.get(objIndex);
            HSSFRow row = sheet.createRow(objIndex + 1);
            for (int i = 0; i < strArray.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellType(CellType.STRING);
                cell.setCellValue(map.get(strArray[i]).toString());
            }
        }
        byte[] bytes = workbook.getBytes();
        return new ByteArrayInputStream(bytes);
    }

    /**
     * 导出Excle文档
     *
     * @param objList  : Excel数据源
     * @param objClass : Excel数据源中的数据类型
     * @param title    : 新建Sheet的名称 ex: title = "员工表";
     * @param strTitle : Sheet各列的标题(第一行各列的名称)ex: strTitle = "代码,姓名";
     * @param strBody  : Sheet各列的取值方法名(各列的值在objClass中get方法名称) ex: strBody = "getCode,getName";
     * @return
     */
    public static void createExcel(List objList, Class objClass, String title, String strTitle, String strBody, String path) {
        // 初始化工作簿
        HSSFWorkbook workbook = initWorkbook(objList, objClass, title, strTitle, strBody);

        try {
            FileOutputStream fos = new FileOutputStream(new File(path));
            workbook.write(fos);

            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化工作簿
     *
     * @param objList  : Excel数据源
     * @param objClass : Excel数据源中的数据类型
     * @param title    : 新建Sheet的名称
     * @param strTitle : Sheet各列的标题(第一行各列的名称)
     * @param strBody  : Sheet各列的取值方法名(各列的值在objClass中get方法名称)
     */
    private static HSSFWorkbook initWorkbook(List objList, Class objClass, String title, String strTitle, String strBody) {
        // 创建工作簿(Excel文件)
        HSSFWorkbook workbook = new HSSFWorkbook();
        setHeadStyle(workbook);
        setbodyStyle(workbook);

        // 创建Excel工作簿的第一个Sheet页
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认的列宽度为15个字节
        sheet.setDefaultColumnWidth(15);
        // 设置默认的行高像素点
        sheet.setDefaultRowHeightInPoints(16);
        // 创建Sheet页的文件头(第一行)
        createTitle(sheet, strTitle);

        // 创建Sheet页的文件体(后续行)
        if (objClass != Map.class) {
            createBody(objList, objClass, sheet, strBody);
        } else {
            createBody4Map(objList, sheet, strBody);
        }

        return workbook;
    }

    /**
     * 创建Excel当前sheet页的头信息
     *
     * @param sheet    : Excel工作簿的一个sheet
     * @param strTitle : sheet头信息列表(sheet第一行各列值)
     */
    private static void createTitle(HSSFSheet sheet, String strTitle) {
        HSSFRow row = sheet.createRow(0); // 创建该页的一行
        String[] strArray = strTitle.split(",");

        for (int i = 0; i < strArray.length; i++) {
            HSSFCell cell = row.createCell(i); // 创建该行的一列
            cell.setCellType(CellType.STRING);
            cell.setCellValue(strArray[i]);
            cell.setCellStyle(headStyle);

            // 自适应宽度
            if ((sheet.getColumnWidth(i)) < cell.getStringCellValue().getBytes().length * 400) {
                sheet.setColumnWidth(i, cell.getStringCellValue().getBytes().length * 400);
            }
        }

    }

    /**
     * 创建Excel当前sheet页的体信息
     *
     * @param objList  : Excel数据源
     * @param objClass : Excel数据源中的数据类型
     * @param sheet    : Excel工作簿的sheet页
     * @param strBody  : Sheet各列的取值方法名(各列的值在objClass中get方法名称)
     */
    private static void createBody(List objList, Class objClass, HSSFSheet sheet, String strBody) {
        String[] targetMethod = strBody.split(",");
        Method[] ms = objClass.getMethods();

        // 循环objList对象列表(生成sheet的行)
        for (int objIndex = 0; objIndex < objList.size(); objIndex++) {
            Object obj = objList.get(objIndex);
            HSSFRow row = sheet.createRow(objIndex + 1);
            // 循环strBody目标方法数组(生成sheet的列)
            for (int strIndex = 0; strIndex < targetMethod.length; strIndex++) {
                String targetMethodName = targetMethod[strIndex];
                // 循环ms方法数组,找到目标方法(strBody中指定的方法)并调用
                for (int i = 0; i < ms.length; i++) {
                    Method srcMethod = ms[i];
                    int len = targetMethodName.indexOf(".") < 0 ? targetMethodName.length() : targetMethodName.indexOf(".");
                    if (srcMethod.getName().equals(targetMethodName.substring(0, len))) {
                        HSSFCell cell = row.createCell(strIndex);
                        cell.setCellStyle(bodyStyle);
                        try {
                            // 如果方法返回一个引用类型的值
                            if (targetMethodName.contains(".")) {
                                cell.setCellType(CellType.STRING);
                                cell.setCellValue(referenceInvoke(targetMethodName, obj));
                                // 如果方法返回一个普通属性
                            } else {
                                Object object = srcMethod.invoke(obj);
                                if (object == null) {
                                    cell.setCellType(CellType.STRING);
                                    cell.setCellValue("");
                                } else {
                                    cell.setCellType(CellType.STRING);
                                    cell.setCellValue((object).toString());
                                }
                                // 自适应宽度
                                String cellValue = cell.getStringCellValue();
                                if ((sheet.getColumnWidth(strIndex)) < cellValue.getBytes().length * 400) {
                                    sheet.setColumnWidth(strIndex, cellValue.getBytes().length * 400);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

    }

    /**
     * 创建Excel当前sheet页的体信息,Excel数据源中的数据类型为Map
     * 暂不支持多级引用
     *
     * @param objList : Excel数据源
     * @param sheet   : Excel工作簿的sheet页
     * @param strBody : Sheet各列对应至数据源Map中的键
     */
    private static void createBody4Map(List objList, HSSFSheet sheet, String strBody) {
        String[] targetKeys = strBody.split(",");

        // 循环objList对象列表(生成sheet的行)
        for (int objIndex = 0; objIndex < objList.size(); objIndex++) {
            Map obj = (Map) objList.get(objIndex);
            HSSFRow row = sheet.createRow(objIndex + 1);
            // 循环strBody属性数组(生成sheet的列)
            for (int strIndex = 0; strIndex < targetKeys.length; strIndex++) {
                String targetKey = targetKeys[strIndex];
                HSSFCell cell = row.createCell(strIndex);
                cell.setCellStyle(bodyStyle);
                Object value = obj.get(targetKey);

                if (value == null) {
                    cell.setCellType(CellType.STRING);
                    cell.setCellValue("");
                } else {
                    cell.setCellType(CellType.STRING);
                    cell.setCellValue((value).toString());
                }
                // 自适应宽度
                String cellValue = cell.getStringCellValue();
                if ((sheet.getColumnWidth(strIndex)) < cellValue.getBytes().length * 400) {
                    sheet.setColumnWidth(strIndex, cellValue.getBytes().length * 400);
                }
            }
        }

    }

    /**
     * 方法返回的是一个对象的引用(如:getHomeplace.getName类型的方法序列)
     * 按方法序列逐层调用直到最后放回基本类型的值
     *
     * @param targetMethod : obj对象所包含的方法列
     * @param obj          : 待处理的对象
     * @return
     */
    private static String referenceInvoke(String targetMethod, Object obj) {
        // 截取方法序列的第一个方法(即截取属于obj对象的方法:getHomeplace())
        String refMethod = targetMethod.substring(0, targetMethod.indexOf("."));
        // 获得后续方法序列(getName())
        targetMethod = targetMethod.substring(targetMethod.indexOf(".") + 1);
        try {
            // 获得第一个方法的执行结果(即obj方法执行的结果:obj.getHomeplace())
            obj = obj.getClass().getMethod(refMethod).invoke(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 如果方法序列没到最后一节
        if (targetMethod.contains(".")) {
            return referenceInvoke(targetMethod, obj);
            // 如果方法序列到达最后一节
        } else {
            try {
                if (obj == null)
                    return "";
                // 通过obj对象获得该方法链的最后一个方法并调用
                Method tarMethod = obj.getClass().getMethod(targetMethod);
                return tarMethod.invoke(obj).toString();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

    }

    public static HSSFCellStyle setHeadStyle(HSSFWorkbook workBook) {
        headStyle = workBook.createCellStyle();

        headStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.SKY_BLUE.getIndex());
        headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headStyle.setBorderBottom(BorderStyle.THIN);
        headStyle.setBorderLeft(BorderStyle.THIN);
        headStyle.setBorderRight(BorderStyle.THIN);
        headStyle.setBorderTop(BorderStyle.THIN);
        headStyle.setAlignment(HorizontalAlignment.CENTER);
        // 生成字体
        if (headFont == null) {
            headFont = workBook.createFont();
        }
        headFont.setColor(HSSFColor.HSSFColorPredefined.VIOLET.getIndex());
        headFont.setFontHeightInPoints((short) 12);
        headFont.setBold(true);
        // 把字体应用到当前的样样式
        headStyle.setFont(headFont);
        return headStyle;

    }

    public static HSSFCellStyle setbodyStyle(HSSFWorkbook workBook) {
        bodyStyle = workBook.createCellStyle();
        bodyStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
        bodyStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        bodyStyle.setBorderBottom(BorderStyle.THIN);
        bodyStyle.setBorderLeft(BorderStyle.THIN);
        bodyStyle.setBorderRight(BorderStyle.THIN);
        bodyStyle.setBorderTop(BorderStyle.THIN);
        bodyStyle.setAlignment(HorizontalAlignment.CENTER);
        bodyStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 生成字体
        if (bodyFont == null) {
            bodyFont = workBook.createFont();
        }
        bodyFont.setBold(false);
        // 把字体应用到当前的样样式
        bodyStyle.setFont(bodyFont);
        return bodyStyle;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值