POI 導出文件以文件流形式返回

POI工具類 


import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class PoiUtils {
	/**
     * 導出Excel
     * @param sheetName sheet名稱
     * @param title 標題
     * @param values 內容
     * @param wb HSSFWorkbook對象
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][]values, HSSFWorkbook wb){

        // 第一步,創建一個HSSFWorkbook,對應一個Excel文件
        if(wb == null){
            wb = new HSSFWorkbook();
        }

        // 第二步,在workbook中添加一個sheet,對應Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);

        // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制
        HSSFRow row = sheet.createRow(0);

        // 第四步,創建單元格,並設置值表頭 設置表頭居中
        HSSFCellStyle style = wb.createCellStyle();
//        style.setAlignment(HorizontalAlignment.CENTER); // 創建一個居中格式

        //聲明列對象
        HSSFCell cell = null;

        //創建標題
        for(int i=0;i<title.length;i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        //創建內容
        for(int i=0;i<values.length;i++){
            row = sheet.createRow(i + 1);
            for(int j=0;j<values[i].length;j++){
                //將內容按順序賦給對應的列對象
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        return wb;
    }

    //發送響應流方法
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

導出接口
 

    @GetMapping("/exportParkOrderByPage")
    @ApiOperation(value = "導出訂單明細信息(默認查詢全部)", notes = "導出訂單明細信息(默認查詢全部)", response = ParkOrder.class)
    public void exportParkOrderByPage(
            @RequestParam(value = "page", required = false, defaultValue = "0") @ApiParam(required = false, defaultValue = "0", value = "當前頁數,默認從0開始") Integer page,
            @RequestParam(value = "limit", required = false, defaultValue = "10") @ApiParam(required = false, defaultValue = "10", value = "每一頁條數,默認10條") Integer limit,
            @RequestParam(value = "pkid", required = false) @ApiParam(required = false, value = "車場名稱") String pkid,
            @RequestParam(value = "payWay", required = false) @ApiParam(required = false, value = "線上線下(0.線上 1.線下)") String payWay,
            @RequestParam(value = "orderSource", required = false) @ApiParam(required = false, value = "訂單來源") String orderSource,
            @RequestParam(value = "userId", required = false) @ApiParam(required = false, value = "操作人") String userId,
            @RequestParam(value = "plateNo", required = false) @ApiParam(required = false, value = "車牌號碼") String plateNo,
            @RequestParam(value = "orderTimeStart", required = false) @ApiParam(required = false, value = "開始訂單時間") String orderTimeStart,
            @RequestParam(value = "orderTimeEnd", required = false) @ApiParam(required = false, value = "結束訂單時間") String orderTimeEnd,
            HttpServletResponse response) {
        try {
            log.info("++++++++++訪問/count/exportParkOrderByPage接口入參:>>>>>>pkid:" + pkid
                    + " payWay:" + payWay
                    + " orderSource:" + orderSource
                    + " userId:" + userId
                    + " plateNo:" + plateNo
                    + " orderTimeStart:" + orderTimeStart
                    + " orderTimeEnd:" + orderTimeEnd);
            limit = Integer.MAX_VALUE;
            Page<ParkOrder> requestPage = new Page<>(page, limit);
            Map<String, Object> requestParam = new HashMap<String, Object>();
            requestParam.put("pkid", pkid);
            requestParam.put("payWay", payWay);
            requestParam.put("orderSource", orderSource);
            requestParam.put("userId", userId);
            requestParam.put("plateNo", plateNo);
            requestParam.put("orderTimeStart", orderTimeStart);
            requestParam.put("orderTimeEnd", orderTimeEnd);
            Page<ParkOrder> parkOrderByPage = parkOrderService.getParkOrderByPage(requestPage, requestParam);
            List<ParkOrder> records = parkOrderByPage.getRecords();
            //excel標題
            String[] title = {"車場名稱", "車牌號碼", "訂單編號", "金額", "已付金額", "未付金額", "折扣金額", "訂單類型", "支付方式", "訂單時間", "訂單來源", "操作人", "備註"};
            //excel文件名
            String fileName = "訂單明細信息" + System.currentTimeMillis() + ".xls";
            //sheet名
            String sheetName = "訂單明細信息表";
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String[][] content = new String[records.size()][title.length];
            for (int i = 0; i < records.size(); i++) {
                //車場名稱
                content[i][0] = records.get(i).getPkName() == null ? "" : records.get(i).getPkName().toString();
                //車牌號碼
                content[i][1] = records.get(i).getPlateNo() == null ? "" : records.get(i).getPlateNo().toString();
                //訂單編號
                content[i][2] = records.get(i).getOrderNo() == null ? "" : records.get(i).getOrderNo().toString();
                //金額
                content[i][3] = records.get(i).getAmount() == null ? "" : records.get(i).getAmount().toString();
                //已付金額
                content[i][4] = records.get(i).getPayAmount() == null ? "" : records.get(i).getPayAmount().toString();
                //未付金額
                content[i][5] = records.get(i).getUnPayAmount() == null ? "" : records.get(i).getUnPayAmount().toString();
                //折扣金額
                content[i][6] = records.get(i).getDiscountAmount() == null ? "" : records.get(i).getDiscountAmount().toString();
                //訂單類型
                content[i][7] = "";
                if (records.get(i).getOrderType() != null && StrUtil.isNotBlank(records.get(i).getOrderType().toString())) {
                    Integer orderType = Integer.valueOf(records.get(i).getOrderType().toString());
                    switch (orderType) {
                        case 1:
                            content[i][7] = "臨時卡繳費";
                            break;
                        case 2:
                            content[i][7] = "月卡繳費";
                            break;
                        case 3:
                            content[i][7] = "VIP卡繳費";
                            break;
                        case 4:
                            content[i][7] = "儲值卡充值";
                            break;
                        case 5:
                            content[i][7] = "臨時卡續期";
                            break;
                        case 6:
                            content[i][7] = "儲值卡繳費";
                            break;
                        case 12:
                            content[i][7] = "車位預定";
                            break;
                    }
                }
                //支付方式
                content[i][8] = "";
                if (records.get(i).getPayWay() != null && StrUtil.isNotBlank(records.get(i).getPayWay().toString())) {
                    Integer payType = Integer.valueOf(records.get(i).getPayWay().toString());
                    switch (payType) {
                        case 1:
                            content[i][8] = "現金";
                            break;
                        case 2:
                            content[i][8] = "微信";
                            break;
                        case 3:
                            content[i][8] = "支付寶";
                            break;
                        case 4:
                            content[i][8] = "網銀";
                            break;
                        case 5:
                            content[i][8] = "電子錢包";
                            break;
                        case 6:
                            content[i][8] = "優免券";
                            break;
                        case 7:
                            content[i][8] = "餘額";
                            break;
                    }
                }
                //訂單時間
                content[i][9] = records.get(i).getOrderTime() == null ? "" : dateFormat.format(records.get(i).getOrderTime());
                //訂單來源
                content[i][10] = "";
                if (records.get(i).getOrderSource() != null && StrUtil.isNotBlank(records.get(i).getOrderSource().toString())) {
                    Integer source = Integer.valueOf(records.get(i).getOrderSource().toString());
                    switch (source) {
                        case 1:
                            content[i][10] = "微信";
                            break;
                        case 2:
                            content[i][10] = "APP";
                            break;
                        case 3:
                            content[i][10] = "中心繳費";
                            break;
                        case 4:
                            content[i][10] = "崗亭繳費";
                            break;
                        case 5:
                            content[i][10] = "管理處";
                            break;
                        case 6:
                            content[i][10] = "第三方平臺";
                            break;
                    }
                }
                //操作人
                content[i][11] = records.get(i).getUserId() == null ? "" : records.get(i).getUserId().toString();
                //備註
                content[i][12] = records.get(i).getRemark() == null ? "" : records.get(i).getRemark().toString();
            }
            //創建HSSFWorkbook
            HSSFWorkbook wb = PoiUtils.getHSSFWorkbook(sheetName, title, content, null);

            //響應到客戶端
            PoiUtils.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
            log.info("++++++++++訪問/count/exportParkOrderByPage接口調用成功>>>>>>");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("++++++++++訪問/count/exportParkOrderByPage接口系統異常原因 : +++++++++" + e.getMessage());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            log.error("++++++++++訪問/count/exportParkOrderByPage接口系統異常原因 : +++++++++" + throwable.getMessage());
        }
    }

前端操作
 

    handleDownload() {
      this.downloadLoading = true
      exportParkOrderByPage(this.listQuery).then(res=>{
        console.log(res)
        var blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet這裏表示xlsx類型
      var downloadElement = document.createElement('a');
      var href = window.URL.createObjectURL(blob); //創建下載的鏈接
      downloadElement.href = href;
      downloadElement.download = '訂單明細.xls'; //下載後文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); //點擊下載
      document.body.removeChild(downloadElement); //下載完成移除元素
      window.URL.revokeObjectURL(href); //釋放掉blob對象 
        this.downloadLoading = false;
      })
    },

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章