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了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM