POI实现Excel导出

Posted wuxun1997

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POI实现Excel导出相关的知识,希望对你有一定的参考价值。

  POI是专门针对微软的文字办公软件Office进行读写支持的框架,这里只说下如何简单的实现数据导出到Excel。这次先看后台:

  先在pom.xml里引入POI的jar包,我之前引入了commons-logging这个jar包了,所以这里排除一下:

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.6</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>

  接着在Controller实现Excel的创建:

    @ResponseBody
    @RequestMapping(value = "exportExcel", method = RequestMethod.GET)
    public void exportExcel(@RequestParam(value = "currentOperator", required = false) String currentOperator,
                            @RequestParam(value = "status", required = false) String status,
                            @RequestParam(value = "createTimeStart", required = false) String createTimeStart,
                            @RequestParam(value = "createTimeEnd", required = false) String createTimeEnd,
                            HttpServletResponse response) {
        List<FlowView> result = null;
        Date createDateStart = null;
        Date createDateEnd = null;


        // 校验输入起始时间格式
        if (createTimeStart != null && !"".equals(createTimeStart.trim())) {
            try {
                createDateStart = sf.parse(createTimeStart);
            } catch (Exception e) {
                LOGGER.error("--queryFlow-- error: ", e);
                try {
                    Utils.printfErrorOutput(response, "The createTimeStart format wrong.");
                } catch (IOException e1) {
                    LOGGER.error("--printfErrorOutput-- error: ", e1);
                }
            }

            // 若结束时间格式不对或不输入,默认为当前时间
            if (createTimeEnd != null && !"".equals(createTimeEnd.trim())) {
                try {
                    createDateEnd = sf.parse(createTimeEnd);
                } catch (ParseException e) {
                    LOGGER.error("--queryFlow-- error: ", e);
                    createDateEnd = new Date();
                }
            } else {
                createDateEnd = new Date();
            }

            // 若结束时间大于起始时间则报错
            if (createDateStart.after(createDateEnd)) {
                try {
                    Utils.printfErrorOutput(response, "The createTimeStart can not after createTimeEnd.");
                } catch (IOException e) {
                    LOGGER.error("--printfErrorOutput-- error: ", e);
                }
            }
        }

        // 取值
        if (currentOperator == null || currentOperator.trim().length() == 0 || "All".equals(currentOperator)) {
            currentOperator = null;
        }

        if (status == null || status.trim().length() == 0 || "All".equals(status)) {
            status = null;
        }

        result = flowService.queryFlows(0, 0, status, currentOperator, createDateStart, createDateEnd);

        if (result == null || result.size() == 0) {
            try {
                Utils.printfErrorOutput(response, "There is no result to export.");
            } catch (IOException e) {
                LOGGER.error("--printfErrorOutput-- error: ", e);
            }
        }

        // 执行导出逻辑
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();

        // 创建sheet页
        HSSFSheet sheet = hssfWorkbook.createSheet("统计表");

        // 创建表头
        createTitle(sheet);

        // 设置日期格式
        HSSFCellStyle dateStyle = hssfWorkbook.createCellStyle();
        dateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

        // 创建各行数据
        for (int i = 0; i < result.size(); i++) {
            FlowView flow = result.get(i);
            if (flow == null) {
                continue;
            }
            HSSFRow row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(flow.getOrderId());
            row.createCell(1).setCellValue(flow.getTestType());
            row.createCell(2).setCellValue(flow.getTestName());
            row.createCell(3).setCellValue(flow.getReviewUrl());
            row.createCell(4).setCellValue(flow.getPayFlow());
            row.createCell(5).setCellValue(flow.getPhotoUrl());
            if (flow.getPurchaseDate() != null) {
                HSSFCell cell6 = row.createCell(6);
                cell6.setCellValue(flow.getPurchaseDate());
                cell6.setCellStyle(dateStyle);
            }
        }
        String fileName = Utils.createFileName("xls");
        if (null == fileName) {
            fileName = "流程表.xls";
        }

        //生成浏览器页,下载文件
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        try {
            OutputStream outputStream = response.getOutputStream();
            response.flushBuffer();
            hssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            LOGGER.error("--queryFlow-- error : ", e);
            try {
                Utils.printfErrorOutput(response, "Export excel failed.");
            } catch (IOException e1) {
                LOGGER.error("--printfErrorOutput-- error: ", e1);
            }
        }
    }

    /**
     * 创建表头
     *
     * @param sheet
     */
    private void createTitle(HSSFSheet sheet) {
        String[] headers = {"订单号", "评测类型", "评测人名称", "支付流水", "支付截图, "下单时间"};
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
    }

  最后看下js,我们在页面有一个导出按钮,点击触发doExport方法:

        function doExport() {
            var status = $(‘#status‘).val();
            var currentOperator = $(‘#currentOperator‘).val();
            var createTimeStart = $(‘#createTimeStart‘).val();
            var createTimeEnd = $(‘#createTimeEnd‘).val();
            if (createTimeEnd != "" && createTimeStart == "") {
                $.messager.show({
                    title: ‘错误‘,
                    msg: ‘输入结束时间则必须输入起始时间.‘
                });
                return;
            }
            var url = "exportExcel?status=" + status + "&currentOperator=" + currentOperator + "&createTimeStart="
                + createTimeStart + "&createTimeEnd=" + createTimeEnd;
            window.location.href = url;
        }

  打完收工,简单是简单,但只能导出数据到扩展名为.xls的Excel文件里,如果你想导出的Excel后缀是xlsx,那么得另外引入jar包,不能通过HSSFWorkbook对象来处理,而是XSSFWorkbook或者SXSSFWorkbook了。

 

以上是关于POI实现Excel导出的主要内容,如果未能解决你的问题,请参考以下文章

Java 利用poi 导出excel表格 如何在导出时自由选择路径?

java poi导出excel

求问 java poi 导出多个sheet页

java poi xwpf操作word生成一个表格怎么合并单元格,求大神指导!

SpringBoot实现Excel导入导出,好用到爆,POI可以扔掉了!

poi导出excel