欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

EasyPoi导出Excel

程序员文章站 2022-07-11 08:27:09
...
											EasyPoi导出Excel

按照模板导出 单个导出

public String exportRewardStatistics(RewardStatistics rewardStatistics) throws Exception {
        rewardStatistics.setTemplateName("RewardStatisticsTempleteForOne.xlsx");
        TemplateExportParams params = new TemplateExportParams(uploadpath + "template/" + rewardStatistics.getTemplateName());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", rewardStatistics.getRealname());
        map.put("userId", rewardStatistics.getUserid());
        map.put("implementWorkload", rewardStatistics.getImplementWorkload().toString());
        map.put("implementWorkShow", "");
        map.put("buildWorkload", rewardStatistics.getBuildWorkload().toString());
        map.put("buildWorkShow", "");
        map.put("learningWorkload", rewardStatistics.getLearningWorkload().toString());
        map.put("learningWorkShow", "一、项目获奖/n1、10.06,部级项目《名称》,军队科技进步三等奖,排名2(5分)/n10.12,部级项目");
        map.put("teachWorkload", rewardStatistics.getTeachWorkload().toString());
        map.put("teachWorkShow", "");
        map.put("awordWorkload", rewardStatistics.getAwordWorkload().toString());
        map.put("awordWorkShow", "");
        workbook = ExcelExportUtil.exportExcel(params, map);
        workbook.setSheetName(0,rewardStatistics.getRealname()+"个人工作量");
        String filename = UUID.randomUUID().toString()+".xlsx";
        FileOutputStream excelFileOutPutStream = new FileOutputStream(getAbsoluteFile(filename));
        workbook.write(excelFileOutPutStream);
        excelFileOutPutStream.flush();
        excelFileOutPutStream.close();
        return filename;
    }

TemplateExportParams params = new TemplateExportParams(uploadpath + “template/” + rewardStatistics.getTemplateName()); 获取模板路径

单个sheet页导出时,将数据拼接成键值对的形式,key值与模板中的属性保持一致。EasyPoi导出Excel

按照模板导出 批量导出

 public String exportRewardStatisticsByIds(String ids, String templateName) throws Exception {
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd-HH_mm_ss");
        Date date = new Date(System.currentTimeMillis());
        String filename = formatter.format(date) + "工作量统计.xlsx";
        String[] idArry = ids.split(",");
        List<String> idList = new ArrayList<>(idArry.length);
        Collections.addAll(idList, idArry);
        if(idList.size() == 1){
            RewardStatistics re = getById(idList.get(0));
            re.setTemplateName(templateName);
            return exportRewardStatistics(re);
        }
        List<RewardStatistics> rewardStatisticses = new ArrayList<RewardStatistics>(this.listByIds(idList));
        TemplateExportParams params = new TemplateExportParams(uploadpath + "template/" + templateName);
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (int j = 0; j < rewardStatisticses.size(); j++) {
            try {
                RewardStatistics rewardStatistics = rewardStatisticses.get(j);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", rewardStatistics.getRealname());
                map.put("userId", rewardStatistics.getUserid());
                map.put("implementWorkload", rewardStatistics.getImplementWorkload().toString());
                map.put("implementWorkShow", "");
                map.put("buildWorkload", rewardStatistics.getBuildWorkload().toString());
                map.put("buildWorkShow", "");
                map.put("learningWorkload", rewardStatistics.getLearningWorkload().toString());
                map.put("learningWorkShow", "一、项目获奖/n1、10.06,部级项目《名称》,军队科技进步三等奖,排名2(5分)/n10.12,部级项目");
                map.put("teachWorkload", rewardStatistics.getTeachWorkload().toString());
                map.put("teachWorkShow", "");
                map.put("awordWorkload", rewardStatistics.getAwordWorkload().toString());
                map.put("awordWorkShow", "");
                mapList.add(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Map<String,Object> result = new HashMap<String, Object>() ;
        result.put("list",mapList);
        params.setSheetName("工作量统计");
        workbook = ExcelExportUtil.exportExcel(params, result);
        FileOutputStream excelFileOutPutStream = new FileOutputStream(getAbsoluteFile(filename));
        workbook.write(excelFileOutPutStream);
        excelFileOutPutStream.flush();
        excelFileOutPutStream.close();
        return filename;
    }

由于批量导出时,只选择单个数据,存在 workbook = ExcelExportUtil.exportExcel(params, result); 这里会报错显示 workbook为空,没有解决掉,因此在前面做了个判断,批量导出只导出单个时,调用单个导出的方法。
批量导出模板需要配置,{{$fe:list t.name…}} $fe:list 表示按照list循环,该命名需要与代码中的List名称一致EasyPoi导出Excel

动态列非模板导出

/**
*
* @param title
* 表格标题名
* @param headers
* 表格属性列名数组 (第一行标题) 标题必须与列名数组对应 不然会移位
* @param Col
* 需要显示的表格属性列名数组 如果是javabean 必须和字段名字一直 如果为Map 必须为Map的key名字对应
* @param dataset
* 需要显示的数据集合,集合泛型支持两种,1:符合javabean风格的类的对象 2:Map类型。此方法支持的
* javabean属性的数据类型有基本数据类型及String,Date,byte
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
* if(pattern == null || pattern.equals("")) pattern = “yyy-MM-dd”; 可以加上判断
* @param userCol
* 这是我自身的一个逻辑
*/

public HSSFWorkbook exportExcel(String title, String[] headers, String[] Col, List<RewardDetail> dataset,String userCol) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.WHITE.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
        // 声明一个画图的*管理器
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        int Cell = 0;
        List<String> userColList =Arrays.asList(userCol.split(","));
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(Cell);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
            Cell ++ ;
        }
        for (int i = 0;i<dataset.size();i++) {
            row = sheet.createRow(i + 1);
            String[] fields = Col;
            Cell = 0;
            for (short j = 0; j < fields.length; j++) {
                String fieldName = fields[j];
                HSSFCell cell = row.createCell(Cell);
                row.setHeightInPoints(40);
                cell.setCellStyle(style2);
                try {
                    Object value = "";
                    Class tCls = null;
                    //从这里开始就是获取单元格对应数据 如果是对象 
                    //根据反射获取对应的属性 如果是map集合,根据key值获取对应属性值
                    //使用这套导出代码,只用关注这里即可,其他地方都是样式设置
                    if(userColList.contains(fieldName)){
                        tCls = dataset.get(i).getTeacherInfo().getClass();
                        String getMethodName = "get"
                                + fieldName.substring(0, 1).toUpperCase()
                                + fieldName.substring(1);
                        Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
                        value = getMethod.invoke(dataset.get(i).getTeacherInfo(), new Object[] {});
                    }else{
                        List<Map<String,List<String>>> list = dataset.get(i).getWorkRewardDetail();
                        for (Map<String,List<String>> map:list) {
                            if(map.containsKey(fieldName)){
                                value = map.get(fieldName);
                            }
                        }
                    }
                    //拼接数据到这里结束
                    if(value == null ) value = "";
                    String textValue = null;
                    textValue = value.toString();
                    if (textValue != null) {
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            HSSFRichTextString richString = new HSSFRichTextString(textValue);
                            HSSFFont font3 = workbook.createFont();
                            font3.setColor(HSSFColor.BLUE.index);
                            richString.applyFont(font3);
                            cell.setCellValue(richString);
                        }
                    }
                    Cell ++ ;
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return workbook;
   }

下面是对单元格数据做判断 由于我的数据基本都是String 类型 因此我没有判断这个 这个可以添加在数据凭借完成后

 					if(value == null ) value = "";
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    if (value instanceof Date) {
                        Date date = (Date) value;
                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                        textValue = sdf.format(date);
                    } else if (value instanceof byte[]) {
                        // 有图片时,设置行高为60px;
                        row.setHeightInPoints(60);
                        // 设置图片所在列宽度为80px,注意这里单位的一个换算
                        sheet.setColumnWidth(Cell, (short) (35.7 * 80));
                        // sheet.autoSizeColumn(i);
                        byte[] bsValue = (byte[]) value;
                        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
                                1023, 255, (short) 6, index, (short) 6, index);
                        anchor.setAnchorType(2);
                        patriarch.createPicture(anchor, workbook.addPicture(
                                bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        textValue = value.toString();
                    }
                    // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
                    if (textValue != null) {
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            HSSFRichTextString richString = new HSSFRichTextString(
                                    textValue);
                            HSSFFont font3 = workbook.createFont();
                            font3.setColor(HSSFColor.BLUE.index);
                            richString.applyFont(font3);
                            cell.setCellValue(richString);
                        }
                    }

样式可以直接调试 sheet.setDefaultColumnWidth(20); 设置单元格默认宽度 row.setHeightInPoints(40);设置行高
EasyPoi导出Excel

相关标签: easypoi导出