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

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