java 工具 之 Excel 模板導出


1.定義工具類
package com.pagi.iiwpp.est.cio.fncreport.common;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Version
 * @Author LIUYAO823
 * @Date 2020-1-6 15:08
 * @Description
 */
@Slf4j
public class ExcelUtils {

    public static void importTemplateSheets(Map<String, Object> dataMap, String path, String fileName) throws IOException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert servletRequestAttributes != null;
        HttpServletResponse response = servletRequestAttributes.getResponse();
        // 重置響應對象
        assert response != null;
        response.reset();
        // 指定下載的文件名--設置響應頭
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        TemplateExportParams params = new TemplateExportParams(path, true);
        try (Workbook workbook = ExcelExportUtil.exportExcel(params, dataMap);
             OutputStream outputStream = response.getOutputStream();
             BufferedOutputStream bufferedOutPut = new BufferedOutputStream(outputStream)
        ) {
            workbook.write(bufferedOutPut);
            log.info("文件【" + fileName + "】導出成功!");
        } catch (Exception e) {
            log.error("【文件操作失敗】:" + e.getMessage());
            response.setHeader("Content-Disposition", String.format("attachment; filename=%s",
                    URLEncoder.encode("導出失敗.xlsx", "utf-8")));
        }finally {
            response.flushBuffer();
        }
    }
}

2.controller 中調用, resultMap 是sql查詢數據得結果集
@GetMapping("/middleData/export")
public void exportFncT1ReportMiddleData(@RequestParam(value = "theDate") @DateTimeFormat(pattern="yyyy-MM-dd") Date theDate) {
    try {
        Map<String, Object> resultMap = fncT1ReportService.selectNCMST1ExportData(theDate);
        String fileName = "不動產金融產品上報_" + StringDateUtil.dateToString(theDate, 1) + ".xlsx";
        ExcelUtils.importTemplateSheets(resultMap, "template/FNC_T1_CIO_DET.xlsx", fileName);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2.數據來源: 假設excel 中有兩個sheet :基礎信息表 和 基礎信息表

@Override
public Map<String, Object> selectNCMST1ExportData(Date theDate) throws Exception {
    Map<String, Object> resultMap = Maps.newHashMap();
    if (theDate == null) {
        throw new Exception("請求處理參數爲空!");
    }
    Map<String, Object> paramMap = Maps.newHashMapWithExpectedSize(11);
    paramMap.put("theDate", StringDateUtil.dateToString(theDate, 3));
    // 基礎信息表
    StringBuilder sb = new StringBuilder("本次導出金融產品數據統計如下:");
    List<IfT1Debt> ifT1DebtList = ifT1DebtService.selectNCMST1DebtInfoList(paramMap);
    resultMap.put("ifT1DebtList", ifT1DebtList); //ifT1DebtList 這個key 要寫如excel 中去
    sb.append("【項目-債權】基礎信息表").append(ifT1DebtList.size()).append("條,");

    // by liulewei187
    //險資明細
    List<IfInsuranceDetails> ifInsuranceDetailList =    ifInsuranceDetailsService.selectNCMST1InsuranceDetailsList(paramMap);
    resultMap.put("ifInsuranceDetailList", ifInsuranceDetailList);
    sb.append("【項目-債權】基礎信息表").append(ifInsuranceDetailList.size()).append("條,");

    log.info(sb.toString());
    return resultMap;
}

Excel 模板中加上一行 屬性定義: 根據你得表字段定義

 

{{!fe: ifT1DebtList t.reportPoint t.currency t.submissionName t.submissionCode fd:(t.theDate;yyyy/MM/dd) t.isPublish t.projectNo t.projectName t.subCompanyCode t.businessLine t.businessLine2 t.businessLineIii t.isEnforcePayment t.isCapitalPool t.riskLine t.ccf t.internalFlag t.creditOrCollFlag t.isPrepayment t.isDirectInvest t.assetTier1 t.assetTier2 t.industryTier1 t.industryTier2 t.industryTier3 t.swCodeGroup t.addressTier1 t.addressTier2 t.detailAddress t.projFundUse t.frontManager t.frontManagerAccount t.midRiskManager t.midRiskManagerAcc t.projYieldRate t.protoInvest fd:(t.projValueDate;yyyy/MM/dd) t.timeLimit t.projPunitiveRate t.extDebtRatingAgency t.extDebtRatingDate t.extDebtRating t.intDebtRatingAgency t.intDebtRatingDate t.intDebtRating t.intDebtRatingLgd t.debtor t.debtSubject t.debtorCodeTypeH t.debtorCodeH t.debtorTradeL1 t.debtorTradeL2 t.debtorTradeL3 t.debtorCIndustryName t.debtorRegaddrL1 t.debtorRegaddrL2 t.debtorAddress t.debtorCorpType t.debtorProjRela t.debtorGuarTotal t.extRatingAgency t.extRatingDate t.extRating t.intRatingAgency t.intRatingDate t.intRating t.intRatingPd t.pawnTotalRate t.basecapitalExplain t.firstResp t.firstRespAcct t.markToParSpread t.valuationCostPreN t.valuationCostN t.sharpeRatioPre t.roracPre t.advRepayDetail t.legalEntitiy t.swCodeGroup t.riskLine t.ccf t.internalFlag t.creditOrCollFlag t.insuranceRiskRatio t.ifrs9ImpairmentMethod t.reserveMethod t.ifrs9EclFlag t.accountClass t.assetNameFin t.assetNoFin t.investDateFir t.investMatureDate t.investCost t.investCostB t.ifrs9ScaleAllN t.ifrs9ScaleAllB t.ifrs9ScaleN t.ifrs9ScaleB t.amortizedCostN t.amortizedCostB t.fairValueN t.fairValueB t.firstCapitalScale t.secondCapitalScale t.thirdCapitalScale t.valuationDate t.inerRate t.valuationCostB t.valuationCostN t.sharpeRatio t.rorac t.riskState t.theYear t.theMonth t.overdueType t.overdueDays t.overdueDaysCapital t.overdueDaysInterest t.defaultType t.receivableInterest t.receivablePrincipal fd:(t.advRepayDate;yyyy/MM/dd) t.advRepayValue t.debtSubjectH t.debtorCodeTypeH t.debtorCodeH t.extRatingAgencyH t.debtorEratH t.stanDebtorIratFir t.debtorIratH t.stanDebtorIrat t.stanDebtorIratPd t.guarantorName t.guarantorCodeType t.guarantorOrgCode t.stanGuarantorIratFir t.stanGuarantorIrat t.extDebtRatingDate t.extDebtRating t.intDebtRatingDate t.intDebtRating t.intDebtRatingLgd t.elRatio t.projectYield t.payInterestFreq t.payInterestMethod t.payPrincipalFreq t.subCompanyCodeType t.subCompanyCodeType t.cridetCompanyName t.cridetCompanyCodeType t.cridetCompanyCode t.isCapitalPool t.isPlatformRaise t.isActiveManagerment t.priority }}

 

4. 使用postman 測試時,send 下拉框 選擇 send and download 可以保存導出得excel

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