Excel导出之白话文

Offer 驾到,掘友接招!我正在参与2022春招系列活动-经验复盘,点击查看 征文活动详情

一、背景介绍

是这么个情况,之前也做过excel的导出用的最原始POI的方法!需要对表头进行拼接,然后在进行填充数据! 后来发现遇到复杂的表头,尤其加样式,还合并单元格,我擦!这不得太麻烦!后来想了想是不是可以定义一个模板,然后读取模板,最后填充数据就行了那!

有了这个想法之后就开始问度妈妈,确实POI也有模板的读取,但是阿里也做了一个EasyExcel来对原生的POI的封装,也提供了模板的读取填充,那还说说什么肯定支持阿里爸爸呀!

接下来的路程是这样的,我们先看一个我之前用原生POI做的导出,然后来一个读取FTP模板文件的导出!(其实读取远程文件可能是项目中常用的,大家可以着重看看!这里用到FTP的下载和上传!)


二、原始方法

使用的依赖

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>4.1.1</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>4.1.1</version>
</dependency>
复制代码

效果图

原生poi效果图.png


臃肿的代码展示(简单的看看就行了,不是重点哦!):

 public Map<String,String> expExcelByJzbg(ExcelJzbg excelJzbg){
        //创建WorkBook实例
        HSSFWorkbook workbook = new HSSFWorkbook();
        //获取第一张工作表
        HSSFSheet sheet = workbook.createSheet("人员情况模板");
        sheet.setColumnWidth(0, (int) Math.ceil((4.73 * 250)));
        sheet.setColumnWidth(1, (int) Math.ceil((5.31 * 250)));
        sheet.setColumnWidth(2, (int) Math.ceil((9.45 * 250)));
        sheet.setColumnWidth(3, (int) Math.ceil((9.45 * 250)));
        sheet.setColumnWidth(4, (int) Math.ceil((9.45 * 250)));
        sheet.setColumnWidth(5, (int) Math.ceil((9.08 * 250)));
        sheet.setColumnWidth(6, (int) Math.ceil((8.2 * 250)));
        sheet.setColumnWidth(7, (int) Math.ceil((6.38 * 250)));
        sheet.setColumnWidth(8, (int) Math.ceil((3.79 * 250)));
        sheet.setColumnWidth(9, (int) Math.ceil((4.18 * 250)));
        sheet.setColumnWidth(10, (int) Math.ceil((14.47 * 250)));
        sheet.setColumnWidth(11, (int) Math.ceil((15.63 * 250)));
        sheet.setColumnWidth(12, (int) Math.ceil((16.36 * 250)));
        sheet.setColumnWidth(13, (int) Math.ceil((21.05 * 250)));
        sheet.setColumnWidth(14, (int) Math.ceil((16.99 * 250)));
        sheet.setColumnWidth(15, (int) Math.ceil((12.09 * 250)));
        sheet.setColumnWidth(16, (int) Math.ceil((18.36 * 250)));
        sheet.setColumnWidth(17, (int) Math.ceil((7.07 * 250)));
        sheet.setColumnWidth(18, (int) Math.ceil((9.96 * 250)));
        sheet.setColumnWidth(19, (int) Math.ceil((13.28 * 250)));
        sheet.setColumnWidth(20, (int) Math.ceil((8.44 * 250)));
        //创建列头单元格样式
        /*第一行*/
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        HSSFFont oneFont = workbook.createFont();
        oneFont.setFontName("方正小标宋简体");
        oneFont.setFontHeightInPoints((short) 18);
        oneFont.setBold(true);
        style.setFont(oneFont);
        style.setWrapText(true);


        HSSFRow row1 = sheet.createRow(0);
        HSSFCell cell11 = row1.createCell(0);
        cell11.setCellStyle(style);
        cell11.setCellValue("集中办公人员基本信息台账");
        row1.setHeight((short) (43 * 20));


        /*第二行*/
        HSSFCellStyle styletwo = workbook.createCellStyle();
        styletwo.setAlignment(HorizontalAlignment.CENTER);
        styletwo.setVerticalAlignment(VerticalAlignment.CENTER);
        HSSFFont twoFont = workbook.createFont();
        twoFont.setFontName("仿宋_GB2312");
        twoFont.setFontHeightInPoints((short) 14);
        styletwo.setFont(twoFont);
        styletwo.setAlignment(HorizontalAlignment.LEFT);
        styletwo.setWrapText(true);


        HSSFRow row2 = sheet.createRow(1);
        HSSFCell cell21 = row2.createCell(0);
        cell21.setCellStyle(styletwo);
        cell21.setCellValue("组别:" + excelJzbg.getOtherValues().get("zb"));

        HSSFCell cell22 = row2.createCell(11);
        cell22.setCellStyle(styletwo);
        cell22.setCellValue(excelJzbg.getOtherValues().get("yearMonth"));

        HSSFCell cell23 = row2.createCell(16);
        cell23.setCellStyle(styletwo);
        cell23.setCellValue("负责人签字:");

        row2.setHeight((short) (28 * 20));


        /*第三行*/
        HSSFCellStyle styleThree = workbook.createCellStyle();
        styleThree.setAlignment(HorizontalAlignment.CENTER);
        styleThree.setVerticalAlignment(VerticalAlignment.CENTER);
        HSSFFont threeFont = workbook.createFont();
        threeFont.setFontName("仿宋");
        threeFont.setFontHeightInPoints((short) 12);
        styleThree.setFont(threeFont);
        styleThree.setWrapText(true);

        HSSFRow row3 = sheet.createRow(2);

        HSSFCell cell3_0 = row3.createCell(0);
        cell3_0.setCellStyle(styleThree);
        cell3_0.setCellValue("序号");

        HSSFCell cell3_1 = row3.createCell(1);
        cell3_1.setCellStyle(styleThree);
        cell3_1.setCellValue("姓名");

        HSSFCell cell3_2 = row3.createCell(2);
        cell3_2.setCellStyle(styleThree);
        cell3_2.setCellValue("出生年月");

        HSSFCell cell3_3 = row3.createCell(3);
        cell3_3.setCellStyle(styleThree);
        cell3_3.setCellValue("身份证号");

        HSSFCell cell3_4 = row3.createCell(4);
        cell3_4.setCellStyle(styleThree);
        cell3_4.setCellValue("手机号码");

        HSSFCell cell3_5 = row3.createCell(5);
        cell3_5.setCellStyle(styleThree);
        cell3_5.setCellValue("职务/职级");

        HSSFCell cell3_6 = row3.createCell(6);
        cell3_6.setCellStyle(styleThree);
        cell3_6.setCellValue("学历");

        HSSFCell cell3_7 = row3.createCell(7);
        cell3_7.setCellStyle(styleThree);
        cell3_7.setCellValue("学位");

        HSSFCell cell3_8 = row3.createCell(8);
        cell3_8.setCellStyle(styleThree);
        cell3_8.setCellValue("性别");

        HSSFCell cell3_9 = row3.createCell(9);
        cell3_9.setCellStyle(styleThree);
        cell3_9.setCellValue("政治面貌");

        HSSFCell cell3_10 = row3.createCell(10);
        cell3_10.setCellStyle(styleThree);
        cell3_10.setCellValue("集中办公时间起");

        HSSFCell cell3_11 = row3.createCell(11);
        cell3_11.setCellStyle(styleThree);
        cell3_11.setCellValue("集中办公时间止");

        HSSFCell cell3_12 = row3.createCell(12);
        cell3_12.setCellStyle(styleThree);
        cell3_12.setCellValue("集中办公发文名称");

        HSSFCell cell3_13 = row3.createCell(13);
        cell3_13.setCellStyle(styleThree);
        cell3_13.setCellValue("集中办公发文文号");

        HSSFCell cell3_14 = row3.createCell(14);
        cell3_14.setCellStyle(styleThree);
        cell3_14.setCellValue("工作单位");

        HSSFCell cell3_15 = row3.createCell(15);
        cell3_15.setCellStyle(styleThree);
        cell3_15.setCellValue("所属省(市)");

        HSSFCell cell3_16 = row3.createCell(16);
        cell3_16.setCellStyle(styleThree);
        cell3_16.setCellValue("工作单位地址");

        HSSFCell cell3_17 = row3.createCell(17);
        cell3_17.setCellStyle(styleThree);
        cell3_17.setCellValue("工作单位邮编");

        HSSFCell cell3_18 = row3.createCell(18);
        cell3_18.setCellStyle(styleThree);
        cell3_18.setCellValue("单位收件人姓名");

        HSSFCell cell3_19 = row3.createCell(19);
        cell3_19.setCellStyle(styleThree);
        cell3_19.setCellValue("单位收件人手机");

        HSSFCell cell3_20 = row3.createCell(20);
        cell3_20.setCellStyle(styleThree);
        cell3_20.setCellValue("备注");

        row3.setHeight((short) (63 * 20));

        /*数据*/
        List<Map<String, String>> values = excelJzbg.getValues();
        int indexRow = 0;
        for (int i = 0; i < values.size(); i++) {
            Map<String,String> oneData = values.get(i);
            HSSFRow row4 = sheet.createRow(i + 3);
            HSSFCell cell4_0 = row4.createCell(0);
            cell4_0.setCellStyle(styleThree);
            cell4_0.setCellValue(i + 1);

            HSSFCell cell4_1 = row4.createCell(1);
            cell4_1.setCellStyle(styleThree);
            cell4_1.setCellValue(oneData.get("jdrymc"));

            HSSFCell cell4_2 = row4.createCell(2);
            cell4_2.setCellStyle(styleThree);
            cell4_2.setCellValue(oneData.get("csny").substring(0,7));

            HSSFCell cell4_3 = row4.createCell(3);
            cell4_3.setCellStyle(styleThree);
            cell4_3.setCellValue(oneData.get("sfzhm"));

            HSSFCell cell4_4 = row4.createCell(4);
            cell4_4.setCellStyle(styleThree);
            cell4_4.setCellValue("");

            HSSFCell cell4_5 = row4.createCell(5);
            cell4_5.setCellStyle(styleThree);
            cell4_5.setCellValue(oneData.get("zwzjdm"));

            HSSFCell cell4_6 = row4.createCell(6);
            cell4_6.setCellStyle(styleThree);
            cell4_6.setCellValue(oneData.get("xl"));

            HSSFCell cell4_7 = row4.createCell(7);
            cell4_7.setCellStyle(styleThree);
            cell4_7.setCellValue(oneData.get("xw"));

            HSSFCell cell4_8 = row4.createCell(8);
            cell4_8.setCellStyle(styleThree);
            cell4_8.setCellValue(oneData.get("xb"));

            HSSFCell cell4_9 = row4.createCell(9);
            cell4_9.setCellStyle(styleThree);
            cell4_9.setCellValue(oneData.get("zzmm"));

            HSSFCell cell4_10 = row4.createCell(10);
            cell4_10.setCellStyle(styleThree);
            cell4_10.setCellValue(oneData.get("jzbgsjq").substring(0,10));

            HSSFCell cell4_11 = row4.createCell(11);
            cell4_11.setCellStyle(styleThree);
            cell4_11.setCellValue(oneData.get("jzbgsjz").substring(0,10));

            HSSFCell cell4_12 = row4.createCell(12);
            cell4_12.setCellStyle(styleThree);
            cell4_12.setCellValue(oneData.get("jzbgfwmc"));

            HSSFCell cell4_13 = row4.createCell(13);
            cell4_13.setCellStyle(styleThree);
            cell4_13.setCellValue(oneData.get("jzbgfwwh"));

            HSSFCell cell4_14 = row4.createCell(14);
            cell4_14.setCellStyle(styleThree);
            cell4_14.setCellValue(oneData.get("gzdw"));

            HSSFCell cell4_15 = row4.createCell(15);
            cell4_15.setCellStyle(styleThree);
            cell4_15.setCellValue(oneData.get("sssf"));

            HSSFCell cell4_16 = row4.createCell(16);
            cell4_16.setCellStyle(styleThree);
            cell4_16.setCellValue(oneData.get("gzdwdz"));

            HSSFCell cell4_17 = row4.createCell(17);
            cell4_17.setCellStyle(styleThree);
            cell4_17.setCellValue(oneData.get("gzdwyb"));

            HSSFCell cell4_18 = row4.createCell(18);
            cell4_18.setCellStyle(styleThree);
            cell4_18.setCellValue(oneData.get("dwsjrxm"));

            HSSFCell cell4_19 = row4.createCell(19);
            cell4_19.setCellStyle(styleThree);
            cell4_19.setCellValue(oneData.get("dwsjrsj"));

            HSSFCell cell4_20 = row4.createCell(20);
            cell4_20.setCellStyle(styleThree);
            cell4_20.setCellValue("");

            row4.setHeight((short) (78.75 * 20));
        }

        HSSFRow row4 = sheet.createRow(values.size() + 3);
        HSSFCell cell4_0 = row4.createCell(15);
        cell4_0.setCellStyle(styleThree);
        cell4_0.setCellValue("经办人签字:");


        CellRangeAddress regionOne = new CellRangeAddress(0, 0, 0, 20);
        sheet.addMergedRegion(regionOne);
        CellRangeAddress regionTwo1 = new CellRangeAddress(1, 1, 0, 10);
        sheet.addMergedRegion(regionTwo1);
        CellRangeAddress regionTwo2 = new CellRangeAddress(1, 1, 11, 15);
        sheet.addMergedRegion(regionTwo2);
        CellRangeAddress regionTwo3 = new CellRangeAddress(1, 1, 16, 20);
        sheet.addMergedRegion(regionTwo3);



        // 生成返回文件
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            workbook.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }


        // 上传FTP
        String expFileName = excelJzbg.getExpFileName();
        if (!expFileName.toLowerCase().endsWith(".xlsx")) expFileName += ".xlsx";
        return fileUploadService.uploadFile(null, toMultipartFile(os.toByteArray(), expFileName), WJLX, excelJzbg.getCzryDm());
    }
复制代码

三、升级版

excel模板

excel模板.png


依赖包

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>easyexcel</artifactId>
  <version>2.2.10</version>
</dependency>
复制代码

实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class ExcelCommon {
    private String czryDm;
    /**
     * 模板名称(注意模板必须是.xlsx后缀)
     */
    private String templateName;
    /**
     * 导出文件名称
     */
    private String expFileName;

    /**
     * 存储的数据
     * 必须存放type
     * values.put(“type”,"01");
     * type=01 List 下面还有数据需要存储的复杂表格
     *
     * mapData,listData是需要填充的数据(谁存在就存储谁)
     * values.put("mapData",mapData);
     * values.put("listData",listData);
     */
    private Map<String, Object> values;

}
复制代码

实现的方法

@Override
    public Map<String, String> expExcel(ExcelCommon excelCommon) {
        try{
            // 1、下载文档模版
            String templateName = excelCommon.getTemplateName();
            if (!templateName.toLowerCase().endsWith(".xlsx")) templateName += ".xlsx";
            byte[] templateBytes = ftpUtil.downLoad(templatePath, templateName);
         
            if (templateBytes == null) {
                Map<String, String> result = new HashMap<>();
                result.put("rtnCode", "1000");
                result.put("rtnMsg", "模版获取失败");
                log.info("获取模版文件失败[" + templateName + "]");
                return result;
            }

            // 2、转换成输入流
            InputStream is = new ByteArrayInputStream(templateBytes);

            // 3、定义输出流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            // 4、定义easyExcel
            ExcelWriter excelWriter = EasyExcel.write(byteArrayOutputStream).withTemplate(is).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();

            // 5、根据数据类型填充数据
            Map<String, Object> values = excelCommon.getValues();
            if (values.containsKey("type") == false) {
                Map<String, String> result = new HashMap<>();
                result.put("rtnCode", "1000");
                result.put("rtnMsg", "values中不存在【type】的key");
                log.info("获取模版文件失败[" + templateName + "]");
                return result;
            }


            String type = (String) values.get("type");
            if ("01".equals(type) == true){
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                if (values.containsKey("mapData") == true) excelWriter.fill(values.get("mapData"), fillConfig, writeSheet);
                if (values.containsKey("listData") == true) excelWriter.fill(values.get("listData"), fillConfig, writeSheet);
            }else{
                if (values.containsKey("mapData") == true) excelWriter.fill(values.get("mapData"), writeSheet);
                if (values.containsKey("listData") == true) excelWriter.fill(values.get("listData"), writeSheet);
            }

            excelWriter.finish();

            // 6、上传FTP
            String expFileName = excelCommon.getExpFileName();
            if (!expFileName.toLowerCase().endsWith(".xlsx")) expFileName += ".xlsx";
            return fileUploadService.uploadFile(null, toMultipartFile(byteArrayOutputStream.toByteArray(), expFileName), "xlsx", excelCommon.getCzryDm());
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
复制代码

效果图:

easyexcel效果图.png


四、总结

写此文的目的就是让大家了解easyExcel模板读取的方法,并且可以进行远程读取导出!希望可以帮助到大家,上面有些关于FTP的方法,如果有需要可以私信我,再这就不贴出来了(不是很方便)~



感谢大家的阅读,我是Alson_Code,一个喜欢把简单问题复杂化,把复杂问题简单化的程序猿! ❤

猜你喜欢

转载自juejin.im/post/7077924901067161630