From 3572ffe48aa9e2b12f7fbdfac78819c48cb6c4d7 Mon Sep 17 00:00:00 2001
From: zhizhijie <zhizhijie@users.noreply.gitee.com>
Date: 星期二, 08 九月 2026 10:35:19 +0800
Subject: [PATCH] docs: M1-城市客运 城市汇总整链回归(C7)测试报告——当月/累计块 0 差异
---
traffic-audit-server/src/main/java/com/trafficaudit/reportexport/service/ReportExportService.java | 4278 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
1 files changed, 4,149 insertions(+), 129 deletions(-)
diff --git a/traffic-audit-server/src/main/java/com/trafficaudit/reportexport/service/ReportExportService.java b/traffic-audit-server/src/main/java/com/trafficaudit/reportexport/service/ReportExportService.java
index 151f652..9fdb6f2 100644
--- a/traffic-audit-server/src/main/java/com/trafficaudit/reportexport/service/ReportExportService.java
+++ b/traffic-audit-server/src/main/java/com/trafficaudit/reportexport/service/ReportExportService.java
@@ -1,26 +1,66 @@
package com.trafficaudit.reportexport.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.trafficaudit.common.util.RegionUtil;
+import com.trafficaudit.dataimport.entity.EnergyVehicleQuarterly;
import com.trafficaudit.dataimport.entity.FreightTurnoverImport;
import com.trafficaudit.dataimport.entity.H2032EnterpriseMonthly;
+import com.trafficaudit.dataimport.entity.InvestmentMonthly;
+import com.trafficaudit.dataimport.entity.CityBusMonthly;
+import com.trafficaudit.dataimport.entity.CityTaxiMonthly;
+import com.trafficaudit.dataimport.entity.InvestmentProject;
+import com.trafficaudit.dataimport.entity.PassengerEnterpriseMonthly;
+import com.trafficaudit.dataimport.entity.PassengerIndividualMonthly;
import com.trafficaudit.dataimport.entity.ScaleSplitTransport;
+import com.trafficaudit.auditengine.entity.AuditResult;
+import com.trafficaudit.auditengine.entity.AuditRun;
+import com.trafficaudit.auditengine.mapper.AuditResultMapper;
+import com.trafficaudit.auditengine.mapper.AuditRunMapper;
+import com.trafficaudit.rulemanage.entity.AuditRule;
+import com.trafficaudit.rulemanage.mapper.AuditRuleMapper;
+import com.trafficaudit.dataimport.mapper.EnergyVehicleQuarterlyMapper;
import com.trafficaudit.dataimport.mapper.FreightTurnoverImportMapper;
import com.trafficaudit.dataimport.mapper.H2032EnterpriseMonthlyMapper;
+import com.trafficaudit.dataimport.mapper.InvestmentMonthlyMapper;
+import com.trafficaudit.dataimport.mapper.CityBusMonthlyMapper;
+import com.trafficaudit.dataimport.mapper.CityTaxiMonthlyMapper;
+import com.trafficaudit.dataimport.mapper.InvestmentProjectMapper;
+import com.trafficaudit.dataimport.mapper.PassengerEnterpriseMonthlyMapper;
+import com.trafficaudit.dataimport.mapper.PassengerIndividualMonthlyMapper;
import com.trafficaudit.dataimport.mapper.ScaleSplitTransportMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.FormulaEvaluator;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.apache.poi.xssf.usermodel.XSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
/**
* 鎶ヨ〃鐢熸垚鏈嶅姟锛�3 绫昏緭鍑烘姤琛�
@@ -37,12 +77,567 @@
private ScaleSplitTransportMapper scaleSplitMapper;
@Resource
private FreightTurnoverImportMapper freightTurnoverMapper;
+ @Resource
+ private PassengerEnterpriseMonthlyMapper passengerMapper;
+ @Resource
+ private PassengerIndividualMonthlyMapper passengerIndividualMapper;
+ @Resource
+ private EnergyVehicleQuarterlyMapper energyMapper;
+ @Resource
+ private InvestmentProjectMapper investProjectMapper;
+ @Resource
+ private InvestmentMonthlyMapper investMonthlyMapper;
+ @Resource
+ private CityBusMonthlyMapper cityBusMapper;
+ @Resource
+ private CityTaxiMonthlyMapper cityTaxiMapper;
+ @Resource
+ private AuditResultMapper auditResultMapper;
+ @Resource
+ private AuditRunMapper auditRunMapper;
+ @Resource
+ private AuditRuleMapper auditRuleMapper;
+ /** 鍩庡競瀹㈣繍妯℃澘鐩綍锛坅pplication.yml city-passenger.template-dir锛� */
+ @Value("${city-passenger.template-dir:docs/鍩庡競瀹㈣繍}")
+ private String templateDir;
+ /** 鑳借�楁眹鎬绘ā鏉跨洰褰曪紙application.yml energy.template-dir锛� */
+ @Value("${energy.template-dir:docs/鍏矾鏃呭+鑳借�梷")
+ private String energyTemplateDir;
+ /** 鍏矾鏃呭杈撳嚭妯℃澘鐩綍锛坅pplication.yml passenger.template-dir锛� */
+ @Value("${passenger.template-dir:docs/鍏矾鏃呭+鑳借��/杈撳嚭}")
+ private String passengerTemplateDir;
+
+ /** 姹囨�诲伐浣滅翱妯℃澘鐩綍锛坅pplication.yml summary.template-dir锛� */
+ @Value("${summary.template-dir:docs/鐢熸垚姹囨�诲ぇ琛▆")
+ private String summaryTemplateDir;
+
+ /** 璐ц繍鎶ヨ〃妯℃澘鐩綍锛坅pplication.yml freight.template-dir锛� */
+ @Value("${freight.template-dir:docs/璐ц繍}")
+ private String freightTemplateDir;
+
+ /** 鎶曡祫鎶ヨ〃妯℃澘鐩綍锛坅pplication.yml investment.template-dir锛� */
+ @Value("${investment.template-dir:docs/鎶曡祫/妯℃澘}")
+ private String investTemplateDir;
+
+ // ==================== 瀵煎嚭鍓嶆暟鎹氨缁牎楠岋紙P0锛氶槻姝㈠鍑虹┖琛級 ====================
+
+ /** 杩斿洖姣忓紶鎶ヨ〃渚濊禆鐨勬暟鎹鏁颁笌缂哄け鎻愮ず */
+ public Map<String, Object> checkExportReady(String period, String mode, List<String> types) {
+ Map<String, Object> result = new LinkedHashMap<>();
+ result.put("period", period);
+ result.put("mode", mode);
+ List<Map<String, Object>> items = new ArrayList<>();
+ for (String t : types) {
+ Map<String, Object> it = new LinkedHashMap<>();
+ it.put("key", t);
+ List<String> notes = new ArrayList<>();
+ int rows;
+ List<String> auditTypes = new ArrayList<>();
+ switch (t) {
+ case "cityDetail":
+ case "freightRank":
+ case "turnoverRank":
+ rows = freightReadyRows(period, mode, notes);
+ auditTypes.add("H2032");
+ break;
+ case "passengerCityDetail":
+ case "passengerMidDetail":
+ case "passengerMidRank":
+ case "passengerMidAnalysis":
+ rows = passengerReadyRows(period, mode, notes);
+ auditTypes.add("H2031");
+ break;
+ case "cityBusDetail":
+ case "cityRailFerryDetail":
+ rows = addReadyCount(() -> cityBusMapper.selectCount(periodQw(period, mode, CityBusMonthly::getReportPeriod)), "鍩庡競鍏氦鏈堟姤", notes);
+ auditTypes.add("CITY_BUS");
+ break;
+ case "cityTaxiDetail":
+ rows = addReadyCount(() -> cityTaxiMapper.selectCount(periodQw(period, mode, CityTaxiMonthly::getReportPeriod)), "宸℃父鍑虹鏈堟姤", notes);
+ auditTypes.add("CITY_TAXI");
+ break;
+ case "cityPassengerCitySum":
+ case "cityPassengerDetailSum":
+ case "cityPassengerSummary":
+ rows = addReadyCount(() -> cityBusMapper.selectCount(periodQw(period, mode, CityBusMonthly::getReportPeriod)), "鍩庡競鍏氦鏈堟姤", notes)
+ + addReadyCount(() -> cityTaxiMapper.selectCount(periodQw(period, mode, CityTaxiMonthly::getReportPeriod)), "宸℃父鍑虹鏈堟姤", notes);
+ auditTypes.add("CITY_BUS");
+ auditTypes.add("CITY_TAXI");
+ break;
+ case "investPlan":
+ case "investFiveYearLogistics":
+ case "investBillion":
+ case "investCounty":
+ rows = addReadyCount(() -> investMonthlyMapper.selectCount(periodQw(period, mode, InvestmentMonthly::getReportPeriod)), "鎶曡祫甯傚窞鍗曡〃/姹囨�绘暟鎹�", notes);
+ auditTypes.add("INVEST");
+ break;
+ case "energySummary":
+ rows = addReadyCount(() -> energyMapper.selectCount(periodQw(period, mode, EnergyVehicleQuarterly::getReportPeriod)), "鑳借�楄溅杈嗗搴︽暟鎹�", notes);
+ auditTypes.add("H204");
+ break;
+ case "wycSplit": {
+ rows = addReadyCount(() -> cityTaxiMapper.selectCount(periodQw(period, mode, CityTaxiMonthly::getReportPeriod)), "宸℃父鍑虹鏈堟姤", notes);
+ try {
+ Map<String, Object> inp = loadWycMonthlyInput(period, mode);
+ if (inp == null) {
+ rows = 0;
+ notes.add("銆婄綉绾﹁溅璁㈠崟鍙婂叏鐪佹�婚噺.xlsx銆嬬己 " + period + " 琛岋紙闇�鍏堢淮鎶ゅ綋鏈堣鍗曚笌鍏ㄧ渷 pin锛�");
+ } else {
+ double pinK = (Double) inp.get("pinK"), pinCK = (Double) inp.get("pinCK");
+ double pinZ = (Double) inp.get("pinZ"), pinCZ = (Double) inp.get("pinCZ");
+ double orderSum = (Double) inp.get("orderSum");
+ if (pinK <= 0 || pinCK <= 0 || pinZ <= 0 || pinCZ <= 0 || orderSum <= 0) {
+ rows = 0;
+ notes.add("缃戠害杞﹁緭鍏� " + period + " 琛屼笉瀹屾暣锛堣鍗�/鍏ㄧ渷 pin 缂哄け锛�");
+ }
+ }
+ } catch (Exception ex) {
+ rows = 0;
+ notes.add("缃戠害杞﹁緭鍏ヨ鍙栧け璐ワ細" + ex.getMessage());
+ }
+ break;
+ }
+ case "summaryWorkbook": {
+ rows = addReadyCount(() -> cityTaxiMapper.selectCount(periodQw(period, mode, CityTaxiMonthly::getReportPeriod)), "宸℃父鍑虹鏈堟姤", notes)
+ + addReadyCount(() -> cityBusMapper.selectCount(periodQw(period, mode, CityBusMonthly::getReportPeriod)), "鍩庡競鍏氦鏈堟姤", notes);
+ if (rows <= 0) notes.add("姹囨�昏〃渚濊禆鐨勫叕浜�/鍑虹鏈堟姤鏁版嵁缂哄け");
+ try {
+ if (resolveSummaryMother(period, mode) == null) {
+ rows = 0;
+ notes.add("docs/鐢熸垚姹囨�诲ぇ琛� 涓嬬己灏戝彲澶嶅埗鐨勬瘝鐗堟眹鎬昏〃");
+ }
+ } catch (Exception ex) {
+ rows = 0;
+ notes.add("姣嶇増瀹氫綅澶辫触锛�" + ex.getMessage());
+ }
+ break;
+ }
+ default:
+ rows = 0;
+ notes.add("鏈煡鎶ヨ〃绫诲瀷锛�" + t);
+ }
+ int auditRows = 0;
+ boolean audited = false;
+ for (String at : auditTypes) {
+ auditRows += auditRowsOf(period, mode, at);
+ audited = audited || auditedMarked(period, mode, at);
+ }
+ if (auditTypes.isEmpty()) audited = true;
+ it.put("rows", rows);
+ it.put("ready", rows > 0);
+ it.put("auditRows", auditRows);
+ it.put("audited", audited);
+ it.put("note", String.join("锛�", notes));
+ items.add(it);
+ }
+ result.put("items", items);
+ return result;
+ }
+
+ // ==================== 鎶ヨ〃鏁版嵁棰勮锛堣交閲忕増锛夛細灏辩华 + 鏈堝害瑕嗙洊 + 鏍稿績鎽樿 + 闂娓呭崟 ====================
+
+ /** 鎶ヨ〃鏁版嵁棰勮锛氬湪瀵煎嚭鍓嶅睍绀烘瘡寮犺〃鐨勫氨缁姸鎬併�佹湀搴﹁鐩栥�佹牳蹇冩寚鏍囨憳瑕佷笌闂娓呭崟 */
+ public Map<String, Object> reportPreview(String period, String mode, List<String> types) {
+ Map<String, Object> ready = checkExportReady(period, mode, types);
+ @SuppressWarnings("unchecked")
+ List<Map<String, Object>> items = (List<Map<String, Object>>) ready.get("items");
+ Map<String, Map<String, Object>> byKey = new LinkedHashMap<>();
+ for (Map<String, Object> it : items) byKey.put((String) it.get("key"), it);
+
+ String year = period != null && period.length() >= 4 ? period.substring(0, 4) : "";
+ String yearPrefix = year + "-";
+ int month = monthOf(period, mode);
+ int yearNum = 0;
+ try { yearNum = Integer.parseInt(year); } catch (Exception ignore) {}
+
+ boolean freight = false, passenger = false, cityBus = false, cityTaxi = false, invest = false, energy = false;
+ for (String t : types) {
+ if (isFreightType(t)) freight = true;
+ else if (isPassengerType(t)) passenger = true;
+ else if ("cityTaxiDetail".equals(t) || "wycSplit".equals(t)) { cityTaxi = true; }
+ else if (isCityPassengerType(t) || "summaryWorkbook".equals(t)) { cityTaxi = true; cityBus = true; }
+ else if (isInvestType(t)) invest = true;
+ else if ("energySummary".equals(t)) energy = true;
+ }
+
+ // 鏈堝害瑕嗙洊锛氳骞� 1..month 涓摢浜涙湀鏈夋簮鏁版嵁
+ Set<Integer> freightCover = new TreeSet<>();
+ Set<Integer> passengerCover = new TreeSet<>();
+ Set<Integer> busCover = new TreeSet<>();
+ Set<Integer> taxiCover = new TreeSet<>();
+ Set<Integer> investCover = new TreeSet<>();
+ if (freight) {
+ FreightTurnoverImport ftProv = loadFreightTurnover(period).get("婀栧寳鐪�");
+ for (int m = 1; m <= month; m++) {
+ if (ftProv != null && freightMonth(ftProv, m) != null) freightCover.add(m);
+ }
+ }
+ if (passenger) {
+ passengerCover.addAll(monthsWithData(() -> passengerMapper.selectList(new LambdaQueryWrapper<PassengerEnterpriseMonthly>().likeRight(PassengerEnterpriseMonthly::getReportPeriod, yearPrefix)),
+ o -> ((PassengerEnterpriseMonthly) o).getReportPeriod(), month));
+ passengerCover.addAll(monthsWithData(() -> passengerIndividualMapper.selectList(new LambdaQueryWrapper<PassengerIndividualMonthly>().likeRight(PassengerIndividualMonthly::getReportPeriod, yearPrefix)),
+ o -> ((PassengerIndividualMonthly) o).getReportPeriod(), month));
+ }
+ if (cityBus) {
+ busCover.addAll(monthsWithData(() -> cityBusMapper.selectList(new LambdaQueryWrapper<CityBusMonthly>().likeRight(CityBusMonthly::getReportPeriod, yearPrefix)),
+ o -> ((CityBusMonthly) o).getReportPeriod(), month));
+ }
+ if (cityTaxi) {
+ taxiCover.addAll(monthsWithData(() -> cityTaxiMapper.selectList(new LambdaQueryWrapper<CityTaxiMonthly>().likeRight(CityTaxiMonthly::getReportPeriod, yearPrefix)),
+ o -> ((CityTaxiMonthly) o).getReportPeriod(), month));
+ }
+ if (invest) {
+ investCover.addAll(monthsWithData(() -> investMonthlyMapper.selectList(new LambdaQueryWrapper<InvestmentMonthly>().likeRight(InvestmentMonthly::getReportPeriod, yearPrefix)),
+ o -> ((InvestmentMonthly) o).getReportPeriod(), month));
+ }
+
+ for (Map.Entry<String, Map<String, Object>> e : byKey.entrySet()) {
+ String t = e.getKey();
+ Map<String, Object> it = e.getValue();
+ List<Map<String, Object>> summary = new ArrayList<>();
+ List<String> problems = new ArrayList<>();
+ List<Integer> missing = new ArrayList<>();
+ List<Integer> coverage = new ArrayList<>();
+ if (Boolean.FALSE.equals(it.get("audited"))) problems.add("璇ユ姤琛ㄦ湡灏氭湭瀹℃牳閫氳繃");
+ if ("wycSplit".equals(t)) {
+ coverage.addAll(taxiCover);
+ missing = missingMonths(taxiCover, month);
+ try {
+ Map<String, Object> inp = loadWycMonthlyInput(period, mode);
+ if (inp == null) {
+ problems.add("缂虹綉绾﹁溅杈撳叆锛氳鍦ㄣ�婄綉绾﹁溅璁㈠崟鍙婂叏鐪佹�婚噺.xlsx銆嬭ˉ " + period + " 琛�");
+ } else {
+ double pinK = (Double) inp.get("pinK"), pinCK = (Double) inp.get("pinCK");
+ double pinZ = (Double) inp.get("pinZ"), pinCZ = (Double) inp.get("pinCZ");
+ double orderSum = (Double) inp.get("orderSum");
+ if (pinK <= 0 || pinCK <= 0 || pinZ <= 0 || pinCZ <= 0 || orderSum <= 0) {
+ problems.add("缃戠害杞﹁緭鍏� " + period + " 琛屼笉瀹屾暣锛堣鍗�/鍏ㄧ渷 pin 缂哄け锛�");
+ } else {
+ addSum(summary, "鍏ㄧ渷缃戠害杞﹀杩愰噺", pinK, "涓囦汉");
+ addSum(summary, "鍏朵腑鍩庡競鍐呭杩愰噺", pinCK, "涓囦汉");
+ addSum(summary, "鍏ㄧ渷缃戠害杞﹀懆杞噺", pinZ, "涓囦汉鍏噷");
+ addSum(summary, "鍏朵腑鍩庡競鍐呭懆杞噺", pinCZ, "涓囦汉鍏噷");
+ addSum(summary, "閮ㄧ骇璁㈠崟鍚堣", orderSum, "鍗�");
+ }
+ }
+ } catch (Exception ex) {
+ problems.add("缃戠害杞﹁緭鍏ヨ鍙栧け璐ワ細" + ex.getMessage());
+ }
+ } else if ("summaryWorkbook".equals(t)) {
+ java.util.Set<Integer> cov = new java.util.TreeSet<>();
+ cov.addAll(busCover);
+ cov.addAll(taxiCover);
+ coverage.addAll(cov);
+ missing = missingMonths(cov, month);
+ try {
+ if (resolveSummaryMother(period, mode) == null) {
+ problems.add("docs/鐢熸垚姹囨�诲ぇ琛� 涓嬬己灏戝彲澶嶅埗鐨勬瘝鐗堟眹鎬昏〃");
+ } else {
+ Map<Integer, Map<String, double[]>> busM = loadCityBusByMonth(yearPrefix, month);
+ Map<Integer, Map<String, double[]>> taxiM = loadCityTaxiByMonth(yearPrefix, month);
+ Map<String, double[]> bc = busM.get(month);
+ Map<String, double[]> tc = taxiM.get(month);
+ if (bc != null && bc.get("鍏ㄧ渷") != null) addSum(summary, "鍩庡競鍏氦瀹㈣繍閲忥紙鍏ㄧ渷褰撴湀锛�", bc.get("鍏ㄧ渷")[0], "涓囦汉");
+ if (tc != null && tc.get("鍏ㄧ渷") != null) addSum(summary, "宸℃父鍑虹瀹㈣繍閲忥紙鍏ㄧ渷褰撴湀锛�", tc.get("鍏ㄧ渷")[0], "涓囦汉");
+ }
+ } catch (Exception ex) {
+ problems.add(ex.getMessage());
+ }
+ } else if (isFreightType(t)) {
+ coverage.addAll(freightCover);
+ missing = missingMonths(freightCover, month);
+ freightPreview(period, month, summary, problems);
+ } else if (isPassengerType(t)) {
+ coverage.addAll(passengerCover);
+ missing = missingMonths(passengerCover, month);
+ passengerPreview(yearNum, month, t, summary, problems);
+ } else if ("cityTaxiDetail".equals(t)) {
+ coverage.addAll(taxiCover);
+ missing = missingMonths(taxiCover, month);
+ cityPassengerPreview(yearPrefix, month, t, summary, problems);
+ } else if (isCityPassengerType(t)) {
+ if ("cityBusDetail".equals(t) || "cityRailFerryDetail".equals(t)) {
+ // 鍏氦/杞ㄩ亾杞浮鏄庣粏鍙緷璧栧叕浜ゆ湀鎶ヨ〃锛堣建閬�/杞浮鏁版嵁鍦ㄥ叕浜よ〃鍐咃級
+ coverage.addAll(busCover);
+ missing = missingMonths(busCover, month);
+ } else {
+ Set<Integer> cov = new TreeSet<>();
+ cov.addAll(busCover);
+ cov.addAll(taxiCover);
+ coverage.addAll(cov);
+ missing = missingMonths(cov, month);
+ }
+ cityPassengerPreview(yearPrefix, month, t, summary, problems);
+ } else if (isInvestType(t)) {
+ coverage.addAll(investCover);
+ // 鎶曡祫涓哄綋鏈堟姤琛紙鏃� 1..N 绱鍙e緞锛夛紝鍙彁绀哄綋鏈堢己澶�
+ if (!investCover.contains(month)) missing.add(month);
+ investPreview(period, mode, summary, problems);
+ } else if ("energySummary".equals(t)) {
+ Long ec = energyMapper.selectCount(periodQw(period, mode, EnergyVehicleQuarterly::getReportPeriod));
+ if (ec != null && ec > 0) coverage.add(month);
+ energyPreview(period, mode, summary, problems);
+ }
+ if (!missing.isEmpty()) {
+ problems.add("缂烘湀鏁版嵁锛�" + joinMonths(missing) + "锛�1~" + month + "鏈堢疮璁¢渶閫愭湀榻愬叏锛�");
+ }
+ it.put("monthCoverage", coverage);
+ it.put("missingMonths", missing);
+ it.put("summary", summary);
+ it.put("problems", problems);
+ }
+ return ready;
+ }
+
+ private boolean isFreightType(String t) {
+ return "cityDetail".equals(t) || "freightRank".equals(t) || "turnoverRank".equals(t);
+ }
+
+ private boolean isPassengerType(String t) {
+ return "passengerCityDetail".equals(t) || "passengerMidDetail".equals(t) || "passengerMidRank".equals(t) || "passengerMidAnalysis".equals(t);
+ }
+
+ private boolean isCityPassengerType(String t) {
+ return "cityBusDetail".equals(t) || "cityRailFerryDetail".equals(t) || "cityPassengerCitySum".equals(t)
+ || "cityPassengerDetailSum".equals(t) || "cityPassengerSummary".equals(t);
+ }
+
+ private boolean isInvestType(String t) {
+ return "investPlan".equals(t) || "investFiveYearLogistics".equals(t) || "investBillion".equals(t) || "investCounty".equals(t);
+ }
+
+ private boolean isEnergyType(String t) {
+ return "energySummary".equals(t);
+ }
+
+ /** 鎸� report_period like 'yyyy-' 缁熻 1..limit 鏈堜腑鏈夋暟鎹殑鏈堜唤锛堝崌搴忥級 */
+ private Set<Integer> monthsWithData(java.util.function.Supplier<java.util.List<?>> rows, java.util.function.Function<Object, String> periodOf, int limit) {
+ Set<Integer> set = new TreeSet<>();
+ for (Object o : rows.get()) {
+ String rp = periodOf.apply(o);
+ if (rp == null) continue;
+ String[] parts = rp.split("-");
+ if (parts.length < 2) continue;
+ try {
+ int m = Integer.parseInt(parts[1]);
+ if (m >= 1 && m <= limit) set.add(m);
+ } catch (Exception ignore) {}
+ }
+ return set;
+ }
+
+ /** 1..limit 涓己澶辩殑鏈堜唤 */
+ private List<Integer> missingMonths(Set<Integer> coverage, int limit) {
+ List<Integer> missing = new ArrayList<>();
+ for (int m = 1; m <= limit; m++) if (!coverage.contains(m)) missing.add(m);
+ return missing;
+ }
+
+ private String joinMonths(List<Integer> months) {
+ StringBuilder sb = new StringBuilder();
+ for (int m : months) {
+ if (sb.length() > 0) sb.append("銆�");
+ sb.append(m).append("鏈�");
+ }
+ return sb.toString();
+ }
+
+ private void addSum(List<Map<String, Object>> summary, String label, Double value, String unit) {
+ Map<String, Object> m = new LinkedHashMap<>();
+ m.put("label", label);
+ m.put("value", value);
+ m.put("unit", unit);
+ summary.add(m);
+ }
+
+ /** 璐ц繍鎽樿锛氬叏鐪佺疮璁¤揣杩愰噺锛堝悎璁�/瑙勪笂/瑙勪笅锛�+ 鍛ㄨ浆閲忥紙鎷嗗垎琛ㄥ叏鐪佺疮璁¤锛� */
+ private void freightPreview(String period, int month, List<Map<String, Object>> summary, List<String> problems) {
+ Map<String, FreightTurnoverImport> ft = loadFreightTurnover(period);
+ Map<String, Double> h2032Cum = loadH2032FreightCumulative(period);
+ ScaleSplitTransport provCum = getProvinceCumulative(period);
+ Double total = freightCum(ft.get("婀栧寳鐪�"), month);
+ Double totalWan = total == null ? null : round(total, 4); // 妯℃澘鍒楀凡鏄竾鍚紝涓嶅啀 梅10000
+ double above = 0.0;
+ for (Double v : h2032Cum.values()) if (v != null) above += v;
+ double aboveWan = round(above / 10000.0, 4);
+ Double belowWan = totalWan == null ? null : round(totalWan - aboveWan, 4);
+ addSum(summary, "鍏ㄧ渷绱璐ц繍閲忥紙鍚堣锛�", totalWan, "涓囧惃");
+ addSum(summary, "鍏朵腑锛氳涓�", aboveWan, "涓囧惃");
+ addSum(summary, "鍏朵腑锛氳涓�", belowWan, "涓囧惃");
+ if (provCum != null) {
+ addSum(summary, "鍏ㄧ渷绱鍛ㄨ浆閲忥紙鍚堣锛�", provCum.getTotalTurnover(), "涓囧惃鍏噷");
+ addSum(summary, "鍏朵腑锛氳涓�", provCum.getAboveScaleTurnover(), "涓囧惃鍏噷");
+ addSum(summary, "鍏朵腑锛氳涓�", provCum.getBelowScaleTurnover(), "涓囧惃鍏噷");
+ } else {
+ problems.add("鎷嗗垎琛ㄦ棤鍏ㄧ渷绱琛岋紙鍛ㄨ浆閲�/瑙勪笂瑙勪笅缂猴級");
+ }
+ if (totalWan == null) problems.add("妯℃澘_璐ц繍閲忓懆杞噺鏃犲叏鐪佺疮璁★紝绱璐ц繍閲忎负绌�");
+ }
+
+ /** 鏃呭鎽樿锛氫紒涓�+涓綋锛堝垎甯傚窞锛夋垨涓彛寰勪紒涓氾紙涓彛寰� 3 琛級 */
+ private void passengerPreview(int yearNum, int month, String type, List<Map<String, Object>> summary, List<String> problems) {
+ Map<Integer, Map<String, PassengerAgg>> data = loadPassengerAggMap();
+ Map<Integer, Map<String, double[]>> indi = loadPassengerIndividualMap();
+ double entPax = 0.0, entTurn = 0.0, indiPax = 0.0, indiTurn = 0.0;
+ boolean anyEnt = false, anyIndi = false;
+ for (int m = 1; m <= month; m++) {
+ PassengerAgg agg = aggOf(data, yearNum, m, "婀栧寳鐪�");
+ if (agg != null) {
+ entPax += agg.passengerTotal / 10000.0;
+ entTurn += agg.turnoverTotal / 10000.0;
+ anyEnt = true;
+ }
+ Map<String, double[]> mm = indi.get(yearNum * 100 + m);
+ if (mm != null) {
+ double[] pv = mm.get("婀栧寳鐪�");
+ if (pv != null) {
+ indiPax += pv[0];
+ indiTurn += pv[1];
+ anyIndi = true;
+ }
+ }
+ }
+ if ("passengerCityDetail".equals(type)) {
+ addSum(summary, "浼佷笟瀹㈣繍閲忕疮璁�", round(entPax, 4), "涓囦汉娆�");
+ addSum(summary, "涓綋瀹㈣繍閲忕疮璁�", round(indiPax, 4), "涓囦汉娆�");
+ addSum(summary, "鍚堣瀹㈣繍閲忕疮璁�", round(entPax + indiPax, 4), "涓囦汉娆�");
+ addSum(summary, "鍚堣鍛ㄨ浆閲忕疮璁�", round(entTurn + indiTurn, 4), "涓囦汉鍏噷");
+ if (!anyEnt && !anyIndi) problems.add("H203-1 鏃呭鏈堟姤涓庝釜浣撴暟鎹潎鏃�");
+ } else {
+ addSum(summary, "涓彛寰勫杩愰噺绱", round(entPax, 4), "涓囦汉娆�");
+ addSum(summary, "涓彛寰勫懆杞噺绱", round(entTurn, 4), "涓囦汉鍏噷");
+ if (!anyEnt) problems.add("H203-1 鏃呭鏈堟姤鏃犱紒涓氭暟鎹�");
+ }
+ }
+
+ /** 鍩庡競瀹㈣繍鎽樿锛氬叕浜�/鍑虹/杞ㄩ亾/杞浮鍏ㄧ渷绱锛堟寚鏍� 0..7锛� */
+ private void cityPassengerPreview(String yearPrefix, int month, String type, List<Map<String, Object>> summary, List<String> problems) {
+ double[] prov = loadCityPassengerCumulative(yearPrefix, month).getOrDefault("鍏ㄧ渷", new double[8]);
+ boolean allZero = true;
+ for (double v : prov) if (v != 0.0) allZero = false;
+ switch (type) {
+ case "cityTaxiDetail":
+ addSum(summary, "鍑虹瀹㈣繍閲忕疮璁�", round(prov[2], 4), "涓囦汉娆�");
+ addSum(summary, "鍑虹鍛ㄨ浆閲忕疮璁�", round(prov[3], 4), "涓囦汉鍏噷");
+ break;
+ case "cityRailFerryDetail":
+ addSum(summary, "杞ㄩ亾瀹㈣繍閲忕疮璁�", round(prov[4], 4), "涓囦汉娆�");
+ addSum(summary, "杞ㄩ亾鍛ㄨ浆閲忕疮璁�", round(prov[5], 4), "涓囦汉鍏噷");
+ addSum(summary, "杞浮瀹㈣繍閲忕疮璁�", round(prov[6], 4), "涓囦汉娆�");
+ addSum(summary, "杞浮鍛ㄨ浆閲忕疮璁�", round(prov[7], 4), "涓囦汉鍏噷");
+ break;
+ case "cityBusDetail":
+ addSum(summary, "鍏氦瀹㈣繍閲忕疮璁�", round(prov[0], 4), "涓囦汉娆�");
+ addSum(summary, "鍏氦鍛ㄨ浆閲忕疮璁�", round(prov[1], 4), "涓囦汉鍏噷");
+ addSum(summary, "杞ㄩ亾瀹㈣繍閲忕疮璁�", round(prov[4], 4), "涓囦汉娆�");
+ addSum(summary, "杞ㄩ亾鍛ㄨ浆閲忕疮璁�", round(prov[5], 4), "涓囦汉鍏噷");
+ addSum(summary, "杞浮瀹㈣繍閲忕疮璁�", round(prov[6], 4), "涓囦汉娆�");
+ addSum(summary, "杞浮鍛ㄨ浆閲忕疮璁�", round(prov[7], 4), "涓囦汉鍏噷");
+ break;
+ default:
+ addSum(summary, "鍏氦瀹㈣繍閲忕疮璁�", round(prov[0], 4), "涓囦汉娆�");
+ addSum(summary, "鍏氦鍛ㄨ浆閲忕疮璁�", round(prov[1], 4), "涓囦汉鍏噷");
+ addSum(summary, "鍑虹瀹㈣繍閲忕疮璁�", round(prov[2], 4), "涓囦汉娆�");
+ addSum(summary, "鍑虹鍛ㄨ浆閲忕疮璁�", round(prov[3], 4), "涓囦汉鍏噷");
+ addSum(summary, "杞ㄩ亾瀹㈣繍閲忕疮璁�", round(prov[4], 4), "涓囦汉娆�");
+ addSum(summary, "杞ㄩ亾鍛ㄨ浆閲忕疮璁�", round(prov[5], 4), "涓囦汉鍏噷");
+ addSum(summary, "杞浮瀹㈣繍閲忕疮璁�", round(prov[6], 4), "涓囦汉娆�");
+ addSum(summary, "杞浮鍛ㄨ浆閲忕疮璁�", round(prov[7], 4), "涓囦汉鍏噷");
+ }
+ if (allZero) problems.add("鍏ㄧ渷绱鍊煎叏涓� 0锛堝叕浜�/鍑虹鏈堟姤鍙兘鏈鍏ワ級");
+ }
+
+ /** 鎶曡祫鎽樿锛氶」鐩暟 + 鏈湀瀹屾垚/鑷勾鍒�/鑷紑濮嬬疮璁� */
+ private void investPreview(String period, String mode, List<Map<String, Object>> summary, List<String> problems) {
+ List<InvestmentMonthly> list = investMonthlyMapper.selectList(periodQw(period, mode, InvestmentMonthly::getReportPeriod));
+ Set<Long> proj = new HashSet<>();
+ double monthDone = 0.0, yearCum = 0.0, startCum = 0.0;
+ for (InvestmentMonthly m : list) {
+ if (m.getProjectId() != null) proj.add(m.getProjectId());
+ monthDone += nz(m.getMonthDone());
+ yearCum += nz(m.getYearCum());
+ startCum += nz(m.getStartCum());
+ }
+ addSum(summary, "鏈夋湀搴﹁褰曢」鐩暟", (double) proj.size(), "涓�");
+ addSum(summary, "鏈湀瀹屾垚鎶曡祫鍚堣", round(monthDone, 2), "涓囧厓");
+ addSum(summary, "鑷勾鍒濈疮璁″畬鎴�", round(yearCum, 2), "涓囧厓");
+ addSum(summary, "鑷紑濮嬬疮璁″畬鎴�", round(startCum, 2), "涓囧厓");
+ if (list.isEmpty()) problems.add("鏃犳姇璧勬湀搴︽暟鎹�");
+ }
+
+ /** 鑳借�楁憳瑕侊細杞﹁締璁板綍鏁� + 鐕冩补娑堣�楀悎璁★紙瀛e害琛紝鎸夋墍閫夊搴︽湯鏈堬級 */
+ private void energyPreview(String period, String mode, List<Map<String, Object>> summary, List<String> problems) {
+ Long cnt = energyMapper.selectCount(periodQw(period, mode, EnergyVehicleQuarterly::getReportPeriod));
+ int rows = cnt == null ? 0 : cnt.intValue();
+ double fuel = 0.0;
+ if (rows > 0) {
+ for (EnergyVehicleQuarterly e : energyMapper.selectList(periodQw(period, mode, EnergyVehicleQuarterly::getReportPeriod))) {
+ fuel += nz(e.getFuelConsumption());
+ }
+ }
+ addSum(summary, "杞﹁締璁板綍鏁�", (double) rows, "鏉�");
+ addSum(summary, "鐕冩补娑堣�楀悎璁�", round(fuel, 2), "鈥�");
+ if (rows == 0) problems.add("璇ュ搴︽棤鑳借�楄溅杈嗘暟鎹�");
+ }
+
+ private int freightReadyRows(String period, String mode, List<String> notes) {
+ return addReadyCount(() -> freightTurnoverMapper.selectCount(periodQw(period, mode, FreightTurnoverImport::getReportPeriod)), "妯℃澘_璐ц繍閲忓懆杞噺", notes)
+ + addReadyCount(() -> scaleSplitMapper.selectCount(periodQw(period, mode, ScaleSplitTransport::getReportPeriod)), "瑙勪笂瑙勪笅鎷嗗垎琛�", notes)
+ + addReadyCount(() -> h2032Mapper.selectCount(periodQw(period, mode, H2032EnterpriseMonthly::getReportPeriod)), "H203-2 璐ц繍鏈堟姤", notes);
+ }
+
+ private int passengerReadyRows(String period, String mode, List<String> notes) {
+ return addReadyCount(() -> passengerMapper.selectCount(periodQw(period, mode, PassengerEnterpriseMonthly::getReportPeriod)), "H203-1 鏃呭鏈堟姤", notes)
+ + addReadyCount(() -> passengerIndividualMapper.selectCount(periodQw(period, mode, PassengerIndividualMonthly::getReportPeriod)), "涓綋瀹㈣繍閲�/鍛ㄨ浆閲�", notes);
+ }
+
+ private <T> LambdaQueryWrapper<T> periodQw(String period, String mode, SFunction<T, ?> periodGetter) {
+ LambdaQueryWrapper<T> qw = new LambdaQueryWrapper<>();
+ if ("year".equals(mode)) {
+ qw.likeRight(periodGetter, period);
+ } else {
+ qw.eq(periodGetter, period);
+ }
+ return qw;
+ }
+
+ private int addReadyCount(java.util.function.Supplier<Long> counter, String label, List<String> notes) {
+ Long cnt = counter.get();
+ if (cnt == null || cnt <= 0) notes.add("缂烘暟鎹細" + label);
+ return cnt == null ? 0 : cnt.intValue();
+ }
+
+ /** 璇ユ姤琛ㄦ湡璇ュ鏍哥被鍨嬪凡浜х敓鐨勫鏍歌褰曟暟锛堝厛瀹℃牳鍐嶅嚭琛ㄧ殑鍓嶇疆妫�鏌ワ級 */
+ private int auditRowsOf(String period, String mode, String ruleType) {
+ List<AuditRule> rules = auditRuleMapper.selectList(new LambdaQueryWrapper<AuditRule>()
+ .eq(AuditRule::getReportType, ruleType)
+ .eq(AuditRule::getIsEnabled, 1));
+ if (rules.isEmpty()) return 0;
+ List<Long> ruleIds = new ArrayList<>();
+ for (AuditRule r : rules) ruleIds.add(r.getId());
+ LambdaQueryWrapper<AuditResult> qw = new LambdaQueryWrapper<>();
+ if ("year".equals(mode)) qw.likeRight(AuditResult::getReportPeriod, period);
+ else qw.eq(AuditResult::getReportPeriod, period);
+ Long cnt = auditResultMapper.selectCount(qw.in(AuditResult::getRuleId, ruleIds));
+ return cnt == null ? 0 : cnt.intValue();
+ }
+
+ /** 璇ユ姤琛ㄦ湡璇ュ鏍哥被鍨嬫槸鍚﹀凡鏈夈�屽鏍搁�氳繃鏍囪銆嶏紙audit_run 琛紱绾夸笅瀹℃牳閫氳繃/绯荤粺瀹℃牳鎵ц鍚庡啓鍏ワ紝瀵煎嚭鍓嶄笉鍐嶆彁绀烘湭瀹℃牳锛� */
+ private boolean auditedMarked(String period, String mode, String ruleType) {
+ LambdaQueryWrapper<AuditRun> qw = new LambdaQueryWrapper<AuditRun>()
+ .eq(AuditRun::getReportType, ruleType);
+ if ("year".equals(mode)) qw.likeRight(AuditRun::getReportPeriod, period);
+ else qw.eq(AuditRun::getReportPeriod, period);
+ Long cnt = auditRunMapper.selectCount(qw);
+ return cnt != null && cnt > 0;
+ }
// ==================== 1. 鐢熸垚_璐ц繍閲忓垎甯傚窞鏄庣粏.xlsx ====================
- public byte[] exportCityDetail(String period) throws Exception {
- int currentMonth = parseMonth(period);
- String year = period.substring(0, 4);
+ public byte[] exportCityDetail(String period, String mode) throws Exception {
+ int currentMonth = monthOf(period, mode);
+ int fillMonths = currentMonth; // 1..N 鏈堬紙N>6 鏃舵ā鏉胯嚜鍔ㄥ悜鍙虫墿鍒楀埌 12 鏈堬級
+ boolean extended = fillMonths > 6;
Map<String, Map<Integer, ScaleSplitTransport>> monthData = loadMonthData(period);
Map<Integer, ScaleSplitTransport> provinceMonthMap = loadProvinceMonthMap(period);
ScaleSplitTransport provinceCum = getProvinceCumulative(period);
@@ -51,85 +646,67 @@
Map<String, Double> h2032FreightCum = loadH2032FreightCumulative(period);
Map<String, FreightTurnoverImport> ftMap = loadFreightTurnover(period);
- XSSFWorkbook wb = new XSSFWorkbook();
- Sheet sheet = wb.createSheet("璐ц繍閲忓垎甯傚窞鏄庣粏");
-
- Row r1 = sheet.createRow(0);
- r1.createCell(0).setCellValue("鎶ヨ〃鏈燂細" + year + "骞�" + currentMonth + "鏈�");
- sheet.createRow(1);
- Row header = sheet.createRow(2);
- header.createCell(0).setCellValue("鍦板尯 鍚嶇О");
- header.createCell(1).setCellValue("鎸囨爣");
- CellStyle dateStyle = wb.createCellStyle();
- dateStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("yyyy-mm-dd"));
- for (int m = 1; m <= currentMonth; m++) {
- Cell c = header.createCell(2 + (m - 1) * 2);
- c.setCellValue(java.sql.Date.valueOf(year + "-" + pad(m) + "-01"));
- c.setCellStyle(dateStyle);
- header.createCell(3 + (m - 1) * 2).setCellValue(m + "鏈堜笌鍘诲勾鍚屾瘮");
- }
- int cumCol = 2 + currentMonth * 2;
- header.createCell(cumCol).setCellValue("绱鍛ㄨ浆閲�");
- header.createCell(cumCol + 1).setCellValue("鍚屾瘮");
- sheet.createRow(3);
-
- int rowIdx = 4;
- String[][] provinceMetrics = {
- {"璐ц繍閲� 锛堜竾鍚級", "freight", "total"},
- {"璐х墿鍛ㄨ浆閲� 锛堜竾鍚ㄥ叕閲岋級", "turnover", "total"},
- {"鍏朵腑瑙勪笂璐ц繍閲� (涓囧惃)", "freight", "above"},
- {"鍏朵腑瑙勪笂璐х墿鍛ㄨ浆閲� (涓囧惃鍏噷)", "turnover", "above"},
- {"鍏朵腑瑙勪笅璐ц繍閲� (涓囧惃)", "freight", "below"},
- {"鍏朵腑瑙勪笅璐х墿鍛ㄨ浆閲� (涓囧惃鍏噷)", "turnover", "below"}
- };
- FreightTurnoverImport ftProvince = ftMap.get("婀栧寳鐪�");
- for (String[] metric : provinceMetrics) {
- Row row = sheet.createRow(rowIdx++);
- row.createCell(0).setCellValue("鍏ㄧ渷");
- row.createCell(1).setCellValue(metric[0]);
- for (int m = 1; m <= currentMonth; m++) {
- setNumeric(row, 2 + (m - 1) * 2, getProvinceMonthValue(provinceMonthMap, ftProvince, m, metric[1], metric[2], h2032Freight));
- setNumeric(row, 3 + (m - 1) * 2, getProvinceMonthYoy(provinceMonthMap, ftProvince, m, metric[1], metric[2]));
- }
- setNumeric(row, cumCol, getProvinceCumValue(provinceCum, ftProvince, metric[1], metric[2], h2032FreightCum, currentMonth));
- setNumeric(row, cumCol + 1, getProvinceCumYoy(provinceCum, ftProvince, metric[1], metric[2], currentMonth));
- }
-
- for (String city : RegionUtil.cityList()) {
- String[][] metrics = {
- {"瑙勪笂+瑙勪笅璐ц繍閲�(涓囧惃)", "freight", "total"},
- {"瑙勪笂璐ц繍閲� (涓囧惃)", "freight", "above"},
- {"瑙勪笅璐ц繍閲� (涓囧惃)", "freight", "below"},
- {"瑙勪笂+瑙勪笅鍛ㄨ浆閲� (涓囧惃鍏噷)", "turnover", "total"},
- {"瑙勪笂璐х墿鍛ㄨ浆閲� (涓囧惃鍏噷)", "turnover", "above"},
- {"瑙勪笅璐х墿鍛ㄨ浆閲� (涓囧惃鍏噷)", "turnover", "below"}
+ // 浠� docs/璐ц繍/鐢熸垚_璐ц繍閲忓垎甯傚窞鏄庣粏.xlsx 涓哄簳绋匡細淇濈暀鏍囬/琛ㄥご/鍚堝苟/鍒楀/鏍峰紡锛屼粎鏇挎崲鏁版嵁鍖�
+ File template = resolveFreightTemplate("鐢熸垚_璐ц繍閲忓垎甯傚窞鏄庣粏.xlsx");
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ if (extended) extendMonthlyColumns(sheet, 2, Integer.parseInt(period.substring(0, 4)), 4, sheet.getLastRowNum());
+ String[][] provinceMetrics = {
+ {"璐ц繍閲� 锛堜竾鍚級", "freight", "total"},
+ {"璐х墿鍛ㄨ浆閲� 锛堜竾鍚ㄥ叕閲岋級", "turnover", "total"},
+ {"鍏朵腑瑙勪笂璐ц繍閲� (涓囧惃)", "freight", "above"},
+ {"鍏朵腑瑙勪笂璐х墿鍛ㄨ浆閲� (涓囧惃鍏噷)", "turnover", "above"},
+ {"鍏朵腑瑙勪笅璐ц繍閲� (涓囧惃)", "freight", "below"},
+ {"鍏朵腑瑙勪笅璐х墿鍛ㄨ浆閲� (涓囧惃鍏噷)", "turnover", "below"}
};
- FreightTurnoverImport ftCity = ftMap.get(city);
- ScaleSplitTransport cum = cumMap.get(city);
- for (String[] metric : metrics) {
- Row row = sheet.createRow(rowIdx++);
- row.createCell(0).setCellValue(RegionUtil.shortName(city));
- row.createCell(1).setCellValue(metric[0]);
- for (int m = 1; m <= currentMonth; m++) {
- setNumeric(row, 2 + (m - 1) * 2, getCityMonthValue(monthData, ftCity, city, m, metric[1], metric[2], h2032Freight));
- setNumeric(row, 3 + (m - 1) * 2, getCityMonthYoy(monthData, ftCity, city, m, metric[1], metric[2]));
- }
- setNumeric(row, cumCol, getCityCumValue(cum, ftCity, metric[1], metric[2], h2032FreightCum, city, currentMonth));
- setNumeric(row, cumCol + 1, getCityCumYoy(cum, ftCity, metric[1], metric[2], currentMonth));
+ FreightTurnoverImport ftProvince = ftMap.get("婀栧寳鐪�");
+ int rowIdx = 4; // 0-based锛氱5琛岃捣涓� 鍏ㄧ渷 6 鎸囨爣
+ for (String[] metric : provinceMetrics) {
+ Row row = sheet.getRow(rowIdx);
+ if (row == null) row = sheet.createRow(rowIdx);
+ fillFreightDetailRow(row, fillMonths, extended ? 26 : 14,
+ m -> getProvinceMonthValue(provinceMonthMap, ftProvince, m, metric[1], metric[2], h2032Freight),
+ m -> getProvinceMonthYoy(provinceMonthMap, ftProvince, m, metric[1], metric[2]),
+ getProvinceCumValue(provinceCum, ftProvince, metric[1], metric[2], h2032FreightCum, currentMonth),
+ getProvinceCumYoy(provinceCum, ftProvince, metric[1], metric[2], currentMonth));
+ rowIdx++;
}
+ for (String city : RegionUtil.cityList()) {
+ String[][] metrics = {
+ {"瑙勪笂+瑙勪笅璐ц繍閲�(涓囧惃)", "freight", "total"},
+ {"瑙勪笂璐ц繍閲� (涓囧惃)", "freight", "above"},
+ {"瑙勪笅璐ц繍閲� (涓囧惃)", "freight", "below"},
+ {"瑙勪笂+瑙勪笅鍛ㄨ浆閲� (涓囧惃鍏噷)", "turnover", "total"},
+ {"瑙勪笂璐х墿鍛ㄨ浆閲� (涓囧惃鍏噷)", "turnover", "above"},
+ {"瑙勪笅璐х墿鍛ㄨ浆閲� (涓囧惃鍏噷)", "turnover", "below"}
+ };
+ FreightTurnoverImport ftCity = ftMap.get(city);
+ ScaleSplitTransport cum = cumMap.get(city);
+ for (String[] metric : metrics) {
+ Row row = sheet.getRow(rowIdx);
+ if (row == null) row = sheet.createRow(rowIdx);
+ fillFreightDetailRow(row, fillMonths, extended ? 26 : 14,
+ m -> getCityMonthValue(monthData, ftCity, city, m, metric[1], metric[2], h2032Freight),
+ m -> getCityMonthYoy(monthData, ftCity, city, m, metric[1], metric[2]),
+ getCityCumValue(cum, ftCity, metric[1], metric[2], h2032FreightCum, city, currentMonth),
+ getCityCumYoy(cum, ftCity, metric[1], metric[2], currentMonth));
+ rowIdx++;
+ }
+ }
+ return toBytes(wb);
}
-
- autoWidth(sheet, cumCol + 2);
- return toBytes(wb);
}
// ==================== 2. 鐢熸垚_璐ц繍閲忔帓鍚�.xlsx ====================
- public byte[] exportFreightRank(String period) throws Exception {
+ public byte[] exportFreightRank(String period, String mode) throws Exception {
String year = period.substring(0, 4);
- int month = parseMonth(period);
+ int month = monthOf(period, mode);
Map<String, FreightTurnoverImport> ftMap = loadFreightTurnover(period);
Map<String, Double> h2032FreightCum = loadH2032FreightCumulative(period);
Map<String, Double> h2032FreightYoy = computeH2032Yoy(period);
+ Map<String, Double> h2032FreightCumLast = loadH2032FreightCumulative(
+ (Integer.parseInt(period.substring(0, 4)) - 1) + period.substring(4));
Map<String, Double> above = new HashMap<>();
Map<String, Double> below = new HashMap<>();
@@ -146,6 +723,15 @@
Double provTotal = freightCum(ftMap.get("婀栧寳鐪�"), month);
Double provBelow = provTotal == null ? null : round(provTotal - provAboveWan, 4);
Double provTotalYoy = freightCumYoy(ftMap.get("婀栧寳鐪�"), month);
+ double provAboveLast = 0.0;
+ for (Double v : h2032FreightCumLast.values()) {
+ if (v != null) provAboveLast += v;
+ }
+ Double provAboveYoy = provAboveLast == 0.0 ? null : round((provAbove - provAboveLast) / provAboveLast, 4);
+ Double provTotalLast = lastFreightCum(ftMap.get("婀栧寳鐪�"), month);
+ Double provBelowLast = provTotalLast == null ? null : round(provTotalLast - provAboveLast / 10000.0, 4);
+ Double provBelowYoy = provBelowLast == null || provBelowLast == 0.0 ? null
+ : round((provBelow - provBelowLast) / provBelowLast, 4);
for (String city : RegionUtil.cityList()) {
Double a = h2032FreightCum.get(city);
@@ -155,81 +741,518 @@
total.put(city, t);
below.put(city, t == null ? null : round(t - aWan, 4));
aboveYoy.put(city, h2032FreightYoy.get(city));
- belowYoy.put(city, null);
+ // 瑙勪笅鍚屾瘮 = (瑙勪笅浠婂勾 - 瑙勪笅鍘诲勾) / 瑙勪笅鍘诲勾锛涜涓嬪幓骞� = 妯℃澘鍘诲勾鍚堣 - H2032鍘诲勾瑙勪笂
+ Double tLast = lastFreightCum(ftMap.get(city), month);
+ Double aLast = h2032FreightCumLast.get(city);
+ double aLastWan = aLast == null ? 0.0 : round(aLast / 10000.0, 4);
+ Double belowLast = tLast == null ? null : round(tLast - aLastWan, 4);
+ Double b = below.get(city);
+ belowYoy.put(city, belowLast == null || belowLast == 0.0 || b == null
+ ? null : round((b - belowLast) / belowLast, 4));
totalYoy.put(city, freightCumYoy(ftMap.get(city), month));
}
- XSSFWorkbook wb = new XSSFWorkbook();
- Sheet sheet = wb.createSheet("璐ц繍閲忔帓鍚�");
- Row title = sheet.createRow(0);
- title.createCell(0).setCellValue(year + "骞�1-" + month + "鏈堝叏鐪佸垎甯傚窞绱瀹屾垚鍏矾璐ц繍閲忔儏鍐�");
-
- int rowIdx = 1;
- rowIdx = writeRankHead(sheet, rowIdx, "璐ц繍閲�", "鍚�");
- rowIdx = writeFreightRankRows(sheet, rowIdx, null, above, below, total, aboveYoy, belowYoy, totalYoy,
- provAboveWan, provBelow, provTotal, null, null, provTotalYoy, true);
+ // ===== 绗簩椤碉紙褰撴湀锛夋暟鎹細瑙勪笂=H2032 褰撴湀銆佸悎璁�=妯℃澘_璐ц繍閲忓懆杞噺褰撴湀鍒椼�佽涓�=宸�硷紱鍚屾瘮=鍘诲勾鍚屾湀 =====
+ Map<String, Map<Integer, Double>> h2032MonthCur = loadH2032FreightByMonth(period);
+ String lastYearPeriod = (Integer.parseInt(year) - 1) + period.substring(4);
+ Map<String, Map<Integer, Double>> h2032MonthLast = loadH2032FreightByMonth(lastYearPeriod);
+ Map<String, Double> monthAbove = new HashMap<>();
+ Map<String, Double> monthBelow = new HashMap<>();
+ Map<String, Double> monthTotal = new HashMap<>();
+ Map<String, Double> monthAboveYoy = new HashMap<>();
+ Map<String, Double> monthBelowYoy = new HashMap<>();
+ Map<String, Double> monthTotalYoy = new HashMap<>();
+ double provMonthAbove = 0.0, provMonthAboveLast = 0.0;
for (String city : RegionUtil.cityList()) {
- rowIdx = writeFreightRankRows(sheet, rowIdx, city, above, below, total, aboveYoy, belowYoy, totalYoy,
- provAboveWan, provBelow, provTotal, null, null, provTotalYoy, false);
+ Double ma = monthFreightWan(h2032MonthCur, city, month);
+ Double maLast = monthFreightWan(h2032MonthLast, city, month);
+ Double mt = freightMonth(ftMap.get(city), month);
+ Double mtLast = lastFreightMonth(ftMap.get(city), month);
+ if (ma != null) provMonthAbove += ma;
+ if (maLast != null) provMonthAboveLast += maLast;
+ monthAbove.put(city, ma);
+ monthTotal.put(city, mt);
+ monthBelow.put(city, mt == null ? null : round(mt - (ma == null ? 0.0 : ma), 4));
+ monthAboveYoy.put(city, growthYoy(ma, maLast));
+ Double mb = monthBelow.get(city);
+ Double mbLast = mtLast == null ? null : round(mtLast - (maLast == null ? 0.0 : maLast), 4);
+ monthBelowYoy.put(city, growthYoy(mb, mbLast));
+ monthTotalYoy.put(city, freightYoy(ftMap.get(city), month));
}
+ Double provMonthAboveWan = provMonthAbove == 0.0 ? null : round(provMonthAbove, 4);
+ Double provMonthTotal = freightMonth(ftMap.get("婀栧寳鐪�"), month);
+ Double provMonthBelow = provMonthTotal == null ? null : round(provMonthTotal - provMonthAbove, 4);
+ Double provMonthAboveYoy = growthYoy(provMonthAbove == 0.0 ? null : provMonthAbove, provMonthAboveLast);
+ Double provMonthTotalLast = lastFreightMonth(ftMap.get("婀栧寳鐪�"), month);
+ Double provMonthBelowLast = provMonthTotalLast == null ? null
+ : round(provMonthTotalLast - provMonthAboveLast, 4);
+ Double provMonthBelowYoy = growthYoy(provMonthBelow, provMonthBelowLast);
+ Double provMonthTotalYoy = freightYoy(ftMap.get("婀栧寳鐪�"), month);
- // 鏈湀鍖哄潡锛堝綋鏈堟爣棰� + 绱鏁版嵁锛屼笌鏍蜂緥缁撴瀯涓�鑷达級
- sheet.createRow(rowIdx++);
- Row title2 = sheet.createRow(rowIdx++);
- title2.createCell(0).setCellValue(year + "骞�" + month + "鏈堝叏鐪佸垎甯傚窞绱瀹屾垚" + "鍏矾璐ц繍閲忔儏鍐�");
- rowIdx = writeRankHead(sheet, rowIdx, "璐ц繍閲�", "鍚�");
- rowIdx = writeFreightRankRows(sheet, rowIdx, null, above, below, total, aboveYoy, belowYoy, totalYoy,
- provAboveWan, provBelow, provTotal, null, null, provTotalYoy, true);
- for (String city : RegionUtil.cityList()) {
- rowIdx = writeFreightRankRows(sheet, rowIdx, city, above, below, total, aboveYoy, belowYoy, totalYoy,
- provAboveWan, provBelow, provTotal, null, null, provTotalYoy, false);
+ // 浠� docs/璐ц繍/鐢熸垚_璐ц繍閲忔帓鍚�.xlsx 涓哄簳绋匡細淇濈暀琛ㄥご/鍚堝苟/鍒楀/鏍峰紡涓� Q/R 鍗犳瘮鍏紡锛屼粎鏇挎崲鏁版嵁
+ File template = resolveFreightTemplate("鐢熸垚_璐ц繍閲忔帓鍚�.xlsx");
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ sheet.getRow(0).getCell(0).setCellValue(year + "骞�" + cumRange(month) + "鍏ㄧ渷鍒嗗競宸炵疮璁″畬鎴愬叕璺揣杩愰噺鎯呭喌");
+ sheet.getRow(22).getCell(0).setCellValue(year + "骞�" + month + "鏈堝叏鐪佸垎甯傚窞瀹屾垚鍏矾璐ц繍閲忔儏鍐�");
+ fillFreightRankBlock(sheet, 3, above, below, total, aboveYoy, belowYoy, totalYoy,
+ provAboveWan, provBelow, provTotal, provAboveYoy, provBelowYoy, provTotalYoy);
+ renameRankMonthHeader(sheet, 24);
+ fillFreightRankBlock(sheet, 25, monthAbove, monthBelow, monthTotal,
+ monthAboveYoy, monthBelowYoy, monthTotalYoy,
+ provMonthAboveWan, provMonthBelow, provMonthTotal,
+ provMonthAboveYoy, provMonthBelowYoy, provMonthTotalYoy);
+ try {
+ wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
+ } catch (Exception e) {
+ log.warn("璐ц繍閲忔帓鍚嶆ā鏉垮叕寮忔眰鍊煎け璐�: {}", e.getMessage());
+ }
+ return toBytes(wb);
}
-
- // 鏈熬绌鸿锛堜笌鏍蜂緥缁撴瀯瀵归綈锛�
- for (int i = 0; i < 4; i++) sheet.createRow(rowIdx++);
-
- autoWidth(sheet, 18);
- return toBytes(wb);
}
// ==================== 3. 鐢熸垚_鍛ㄨ浆閲忔帓鍚�.xlsx ====================
- public byte[] exportTurnoverRank(String period) throws Exception {
+ public byte[] exportTurnoverRank(String period, String mode) throws Exception {
String year = period.substring(0, 4);
- int month = parseMonth(period);
+ int month = monthOf(period, mode);
Map<String, ScaleSplitTransport> cumMap = loadCumulativeMap(period);
ScaleSplitTransport province = getProvinceCumulative(period);
- XSSFWorkbook wb = new XSSFWorkbook();
- Sheet sheet = wb.createSheet("鍛ㄨ浆閲忔帓鍚�");
-
- Row title = sheet.createRow(0);
- title.createCell(0).setCellValue(year + "骞�1-" + month + "鏈堝叏鐪佸垎甯傚窞绱瀹屾垚鍏矾璐х墿杩愯緭鍛ㄨ浆閲忔儏鍐�");
-
- int rowIdx = 1;
- rowIdx = writeRankHead(sheet, rowIdx, "鍛ㄨ浆閲�", "鍚ㄥ叕閲�");
- rowIdx = writeTurnoverRankRows(sheet, rowIdx, null, cumMap, province, true);
- for (String city : RegionUtil.cityList()) {
- rowIdx = writeTurnoverRankRows(sheet, rowIdx, city, cumMap, province, false);
+ // 褰撴湀锛堢浜岄〉锛夛細鍛ㄨ浆閲忔媶鍒嗚〃 MONTH 琛岋紙鍚綋鏈堝悓姣旓級
+ Map<String, ScaleSplitTransport> monthTurnover = new HashMap<>();
+ for (ScaleSplitTransport rec : scaleSplitMapper.selectList(
+ new LambdaQueryWrapper<ScaleSplitTransport>()
+ .eq(ScaleSplitTransport::getPeriodType, "MONTH")
+ .eq(ScaleSplitTransport::getReportPeriod, period))) {
+ String name = RegionUtil.normalizeCityName(rec.getRegionName());
+ if (name != null) monthTurnover.put(name, rec);
}
+ ScaleSplitTransport provinceMonth = monthTurnover.remove("婀栧寳鐪�");
- // 鏈湀鍖哄潡锛堝綋鏈堟爣棰� + 绱鏁版嵁锛屼笌鏍蜂緥缁撴瀯涓�鑷达級
- sheet.createRow(rowIdx++);
- Row title2 = sheet.createRow(rowIdx++);
- title2.createCell(0).setCellValue(year + "骞�" + month + "鏈堝叏鐪佸垎甯傚窞绱瀹屾垚" + "鍏矾璐х墿杩愯緭鍛ㄨ浆閲忔儏鍐�");
- rowIdx = writeRankHead(sheet, rowIdx, "鍛ㄨ浆閲�", "鍚ㄥ叕閲�");
- rowIdx = writeTurnoverRankRows(sheet, rowIdx, null, cumMap, province, true);
- for (String city : RegionUtil.cityList()) {
- rowIdx = writeTurnoverRankRows(sheet, rowIdx, city, cumMap, province, false);
+ // 浠� docs/璐ц繍/鐢熸垚_鍛ㄨ浆閲忔帓鍚�.xlsx 涓哄簳绋匡細淇濈暀琛ㄥご/鍚堝苟/鍒楀/鏍峰紡锛屼粎鏇挎崲鏁版嵁锛決/R 鍗犳瘮涓烘ā鏉跨紦瀛樺�硷紝鎸夋柊鏁版嵁閲嶇畻
+ File template = resolveFreightTemplate("鐢熸垚_鍛ㄨ浆閲忔帓鍚�.xlsx");
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ sheet.getRow(0).getCell(0).setCellValue(year + "骞�" + cumRange(month) + "鍏ㄧ渷鍒嗗競宸炵疮璁″畬鎴愬叕璺揣鐗╄繍杈撳懆杞噺鎯呭喌");
+ sheet.getRow(22).getCell(0).setCellValue(year + "骞�" + month + "鏈堝叏鐪佸垎甯傚窞瀹屾垚鍏矾璐х墿杩愯緭鍛ㄨ浆閲忔儏鍐�");
+ fillTurnoverRankBlock(sheet, 3, cumMap, province);
+ renameRankMonthHeader(sheet, 24);
+ fillTurnoverRankBlock(sheet, 25, monthTurnover, provinceMonth);
+ return toBytes(wb);
}
-
- // 鏈熬绌鸿锛堜笌鏍蜂緥缁撴瀯瀵归綈锛�
- for (int i = 0; i < 4; i++) sheet.createRow(rowIdx++);
-
- autoWidth(sheet, 18);
- return toBytes(wb);
}
+ /** 璐ц繍鎶ヨ〃妯℃澘瀹氫綅锛坉ocs/璐ц繍锛� */
+ private File resolveFreightTemplate(String fileName) throws Exception {
+ return resolveAnyTemplate(freightTemplateDir, fileName);
+ }
+
+ /** 鍐欒揣杩愭ā鏉挎暟鎹崟鍏冩牸锛氬叕寮忓垪涓嶅姩锛涙湁鍊煎厛娓呯┖鍐嶅啓锛圥OI 瀵瑰叕寮忓崟鍏冩牸鍙洿鏂扮紦瀛橈級锛屾棤鍊兼竻绌烘ā鏉挎牱渚� */
+ private void setFreightCell(Row row, int idx, Double v) {
+ Cell c = row.getCell(idx);
+ if (c != null && c.getCellType() == CellType.FORMULA) return;
+ if (c == null) c = row.createCell(idx);
+ c.setBlank();
+ if (v != null) c.setCellValue(v);
+ }
+
+ private void setFreightCell(Row row, int idx, Integer v) {
+ if (v == null) {
+ setFreightCell(row, idx, (Double) null);
+ } else {
+ setFreightCell(row, idx, v.doubleValue());
+ }
+ }
+
+ // ==================== 鏈堝害妯℃澘鑷姩鎵╁垪锛�1-6鏈� 鈫� 1-12鏈堬級 ====================
+
+ /** 鏈堝害妯℃澘鍚戝彸鎵╁垪锛氱疮璁″垪锛�14/15锛夌Щ鍒版湯灏撅紙26/27锛夛紝7..12 鏈堝垪鐢� 1 鏈堝垪鍏嬮殕锛堣〃澶�/鏍峰紡/鍏紡寮曠敤鍚屾锛� */
+ private void extendMonthlyColumns(Sheet sheet, int headerRow, int year, int dataStartRow, int dataEndRow) {
+ moveColumnPair(sheet, headerRow, 14, 26, dataEndRow); // 绱/绱鍚屾瘮 鈫� AA/AB
+ for (int m = 7; m <= 12; m++) {
+ int dst = 2 + (m - 1) * 2;
+ cloneColumnPair(sheet, headerRow, 2, 3, dst, dst + 1, year, m, dataStartRow, dataEndRow);
+ }
+ fixCumulativeFormulas(sheet, headerRow, dataEndRow); // AA 绱鍏紡 = 12 涓湀鍊间箣鍜�
+ }
+
+ /** 鎶婁竴鍒楀锛堝�煎垪+鍚屾瘮鍒楋級浠� src 绉诲埌 dst锛堝惈琛ㄥご/鏁版嵁/鏍峰紡/鍚堝苟/鍒楀锛夛紝src 鍐呭娓呯┖ */
+ private void moveColumnPair(Sheet sheet, int headerRow, int src, int dst, int lastRow) {
+ for (int r = headerRow; r <= lastRow; r++) {
+ copyCellForColumn(sheet, r, src, r, dst, false);
+ copyCellForColumn(sheet, r, src + 1, r, dst + 1, false);
+ clearCellContent(sheet, r, src);
+ clearCellContent(sheet, r, src + 1);
+ }
+ moveMergedRegion(sheet, src, dst);
+ moveMergedRegion(sheet, src + 1, dst + 1);
+ copyColumnWidth(sheet, src, dst);
+ copyColumnWidth(sheet, src + 1, dst + 1);
+ }
+
+ /** 鎶� 1 鏈堝垪瀵瑰厠闅嗕负 m 鏈堝垪瀵癸細琛ㄥご鏂囨湰/鏃ユ湡淇銆佹牱寮忓鍒躲�侀潪璺ㄧ翱鍏紡鍏嬮殕骞跺悓姝ュ垪寮曠敤 */
+ private void cloneColumnPair(Sheet sheet, int headerRow, int srcVal, int srcYoy, int dstVal, int dstYoy,
+ int year, int month, int dataStartRow, int dataEndRow) {
+ for (int r = headerRow; r <= dataEndRow; r++) {
+ boolean dataZone = r >= dataStartRow;
+ cloneCellForMonth(sheet, r, srcVal, dstVal, year, month, dataZone);
+ cloneCellForMonth(sheet, r, srcYoy, dstYoy, year, month, dataZone);
+ }
+ cloneMergedRegion(sheet, srcVal, dstVal);
+ cloneMergedRegion(sheet, srcYoy, dstYoy);
+ copyColumnWidth(sheet, srcVal, dstVal);
+ copyColumnWidth(sheet, srcYoy, dstYoy);
+ }
+
+ /** 澶嶅埗鍗曟牸锛歮ove=false 鍘熸牱澶嶅埗锛沵ove=true 琛ㄥご鏂囨湰/鏃ユ湡淇銆佹暟鎹尯浠呮牱寮�+闈炶法绨垮叕寮忥紙鍒楀紩鐢ㄥ悓姝ワ級 */
+ private void copyCellForColumn(Sheet sheet, int r, int srcC, int dstR, int dstC, boolean monthClone) {
+ Row srcRow = sheet.getRow(r);
+ if (srcRow == null) return;
+ Cell src = srcRow.getCell(srcC);
+ if (src == null) return;
+ Cell dst = getOrCreateCell(sheet, dstR, dstC);
+ dst.setBlank();
+ dst.setCellStyle(src.getCellStyle());
+ if (!monthClone) {
+ if (src.getCellType() == CellType.FORMULA) {
+ String f = src.getCellFormula();
+ if (f != null && !f.contains("#REF!")) dst.setCellFormula(f);
+ } else if (src.getCellType() == CellType.STRING) {
+ dst.setCellValue(src.getStringCellValue());
+ } else if (src.getCellType() == CellType.NUMERIC) {
+ dst.setCellValue(src.getNumericCellValue());
+ } else if (src.getCellType() == CellType.BOOLEAN) {
+ dst.setCellValue(src.getBooleanCellValue());
+ }
+ }
+ }
+
+ /** 鍏嬮殕鍗曟牸鍒扮洰鏍囨湀鍒楋細琛ㄥご琛岋紙dataZone=false锛変慨姝f湀浠�/骞翠唤鏂囨湰鎴栨棩鏈燂紱鏁版嵁鍖轰粎鏍峰紡+闈炶法绨垮叕寮忓厠闅� */
+ private void cloneCellForMonth(Sheet sheet, int r, int srcC, int dstC, int year, int month, boolean dataZone) {
+ Row srcRow = sheet.getRow(r);
+ if (srcRow == null) return;
+ Cell src = srcRow.getCell(srcC);
+ if (src == null) return;
+ Cell dst = getOrCreateCell(sheet, r, dstC);
+ dst.setBlank();
+ dst.setCellStyle(src.getCellStyle());
+ if (!dataZone) {
+ if (src.getCellType() == CellType.NUMERIC && org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(src)) {
+ java.util.Calendar cal = java.util.Calendar.getInstance();
+ cal.set(year, month - 1, 1, 0, 0, 0);
+ cal.clear(java.util.Calendar.MILLISECOND);
+ dst.setCellValue(cal.getTime());
+ } else if (src.getCellType() == CellType.STRING) {
+ String t = src.getStringCellValue();
+ if (t != null && !t.isEmpty()) {
+ dst.setCellValue(t.replaceFirst("^\\d{4}骞�", year + "骞�").replaceFirst("(\\d+)鏈�", month + "鏈�"));
+ }
+ }
+ return;
+ }
+ // 鏁版嵁鍖猴細浠呭鍒舵牱寮忥紱闈炶法绨裤�侀潪 #REF! 鐨勫叕寮忓厠闅嗗苟鍚屾鏈堝�煎垪寮曠敤
+ if (src.getCellType() == CellType.FORMULA) {
+ String f = src.getCellFormula();
+ if (f != null && !f.contains("[") && !f.contains("#REF!")) {
+ dst.setCellFormula(shiftMonthFormula(f, colLetter(dstC)));
+ }
+ }
+ }
+
+ /** 鍏紡鍒楀紩鐢ㄥ钩绉伙細鏈〃鏈堝�煎垪锛圕/E/G/I/K/M/O/Q/S/U/W/Y锛夆啋 鐩爣鍒楀瓧姣嶏紱鎺掗櫎璺ㄧ翱 [..]! 寮曠敤 */
+ private String shiftMonthFormula(String formula, String dstColLetter) {
+ return formula.replaceAll("(?<![A-Za-z0-9\\[\\]!])([CEGIKMOQSUWY])(\\d+)", dstColLetter + "$2");
+ }
+
+ /** AA 绱鍒楀叕寮忛噸鍐欎负 12 涓湀鍊间箣鍜岋紙妯℃澘鍘熶负 1-6 鏈堜箣鍜岋級 */
+ private void fixCumulativeFormulas(Sheet sheet, int headerRow, int dataEndRow) {
+ for (int r = headerRow; r <= dataEndRow; r++) {
+ Row row = sheet.getRow(r);
+ if (row == null) continue;
+ Cell c = row.getCell(26);
+ if (c == null || c.getCellType() != CellType.FORMULA) continue;
+ String f = c.getCellFormula();
+ if (f == null) continue;
+ java.util.regex.Matcher m = java.util.regex.Pattern
+ .compile("(?<![A-Za-z0-9\\[\\]!])([CEGIKMOQSUWY])(\\d+)").matcher(f);
+ if (!m.find()) continue;
+ int rowNum = Integer.parseInt(m.group(2));
+ StringBuilder sb = new StringBuilder();
+ for (char col : new char[]{'C', 'E', 'G', 'I', 'K', 'M', 'O', 'Q', 'S', 'U', 'W', 'Y'}) {
+ if (sb.length() > 0) sb.append("+");
+ sb.append(col).append(rowNum);
+ }
+ c.setCellFormula(sb.toString());
+ }
+ }
+
+ /** 鍚堝苟鍗曞厓鏍硷細src 鍗曞垪鍚堝苟 鈫� dst 鍒楋紙鍚屽舰鐘讹級锛屽苟绉婚櫎鍘熷悎骞� */
+ private void moveMergedRegion(Sheet sheet, int srcCol, int dstCol) {
+ java.util.List<CellRangeAddress> moves = new java.util.ArrayList<>();
+ for (CellRangeAddress m : sheet.getMergedRegions()) {
+ if (m.getFirstColumn() == srcCol && m.getLastColumn() == srcCol) moves.add(m);
+ }
+ for (CellRangeAddress m : moves) {
+ sheet.addMergedRegion(new CellRangeAddress(m.getFirstRow(), m.getLastRow(), dstCol, dstCol));
+ for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--) {
+ if (sheet.getMergedRegion(i).equals(m)) {
+ sheet.removeMergedRegion(i);
+ break;
+ }
+ }
+ }
+ }
+
+ /** 鍚堝苟鍗曞厓鏍硷細src 鍗曞垪鍚堝苟 鈫� dst 鍒楋紙鍚屽舰鐘讹紝淇濈暀鍘熷悎骞讹級 */
+ private void cloneMergedRegion(Sheet sheet, int srcCol, int dstCol) {
+ for (CellRangeAddress m : sheet.getMergedRegions()) {
+ if (m.getFirstColumn() == srcCol && m.getLastColumn() == srcCol) {
+ sheet.addMergedRegion(new CellRangeAddress(m.getFirstRow(), m.getLastRow(), dstCol, dstCol));
+ }
+ }
+ }
+
+ private void copyColumnWidth(Sheet sheet, int src, int dst) {
+ try {
+ int w = sheet.getColumnWidth(src);
+ if (w > 0) sheet.setColumnWidth(dst, w);
+ } catch (Exception ignore) { }
+ }
+
+ private Cell getOrCreateCell(Sheet sheet, int r, int c) {
+ Row row = sheet.getRow(r);
+ if (row == null) row = sheet.createRow(r);
+ Cell cell = row.getCell(c);
+ if (cell == null) cell = row.createCell(c);
+ return cell;
+ }
+
+ private void clearCellContent(Sheet sheet, int r, int c) {
+ Row row = sheet.getRow(r);
+ if (row == null) return;
+ Cell cell = row.getCell(c);
+ if (cell != null) cell.setBlank();
+ }
+
+ private String colLetter(int colIdx) {
+ return org.apache.poi.ss.util.CellReference.convertNumToColString(colIdx);
+ }
+
+ /** 鏃呭鍒嗗競宸炴湀鍊硷紙0=瀹㈣繍閲�/1=鍛ㄨ浆閲�/2=涓綋瀹㈣繍閲�/3=涓綋鍛ㄨ浆閲忥紱0/1=浼佷笟H2031+涓綋锛�2026-09-03 鍙e緞纭锛� */
+ private double passengerMonthVal(Map<Integer, Map<String, PassengerAgg>> data, Map<Integer, Map<String, double[]>> indi,
+ int year, int month, String region, int metricIdx) {
+ if (metricIdx == 0 || metricIdx == 1) { // 瀹㈣繍閲�/鍛ㄨ浆閲忔�昏锛氫紒涓�+涓綋
+ PassengerAgg agg = aggOf(data, year, month, region);
+ double ent = agg == null ? 0.0
+ : (metricIdx == 0 ? agg.passengerTotal / 10000.0 : agg.turnoverTotal / 10000.0);
+ double ind = individualVal(indi, year, month, region, metricIdx == 0 ? 0 : 1);
+ return ent + ind;
+ }
+ return individualVal(indi, year, month, region, metricIdx - 2);
+ }
+
+ /** 鏃呭绱鍚屾瘮锛堝幓骞� 1..months 鏈堢疮璁★級锛氭棤鍘诲勾鏁版嵁杩斿洖 null */
+ private Double passengerCumYoy(Map<Integer, Map<String, PassengerAgg>> data, Map<Integer, Map<String, double[]>> indi,
+ int year, int months, String region, int metricIdx) {
+ double v = 0.0, lv = 0.0;
+ for (int m = 1; m <= months; m++) {
+ v += passengerMonthVal(data, indi, year, m, region, metricIdx);
+ lv += passengerMonthVal(data, indi, year - 1, m, region, metricIdx);
+ }
+ return lv == 0.0 ? null : (v - lv) / lv;
+ }
+
+ /** 涓彛寰勬湀鍚屾瘮锛歬=-1 琛ㄧず鎬昏锛堢彮绾�+鍏氦涔嬪拰锛屽嚭绉�/缃戠害杞︽棤婧愭暟鎹寜 0锛夛紱鏃犲幓骞存暟鎹暀绌� */
+ private void fillMidYoyCell(Cell c, Map<Integer, Map<String, double[][]>> mid, int year, int month,
+ String area, int k, boolean volume) {
+ double v = 0.0, lv = 0.0;
+ if (k == -1) {
+ for (int kk = 1; kk <= 4; kk++) {
+ if (kk >= 3) continue;
+ v += midClassVal(mid, year, month, area, kk, volume);
+ lv += midClassVal(mid, year - 1, month, area, kk, volume);
+ }
+ } else if (k <= 2) {
+ v = midClassVal(mid, year, month, area, k, volume);
+ lv = midClassVal(mid, year - 1, month, area, k, volume);
+ }
+ c.setBlank();
+ if (v != 0.0 && lv != 0.0) c.setCellValue(round((v - lv) / lv, 4));
+ }
+
+ /** 涓彛寰勭疮璁″悓姣斿垪锛�1..months 鏈堢疮璁★紱k=-1 鎬昏 = 鐝嚎+鍏氦锛� */
+ private void fillMidCumYoyColumn(Sheet sheet, Map<Integer, Map<String, double[][]>> mid, int year,
+ int months, int colIdx) {
+ List<String> areas = midTemplateAreas();
+ for (int r0 = 4; r0 <= sheet.getLastRowNum(); r0++) {
+ int rr = r0 + 1;
+ int blockOffset = -1;
+ boolean volume = false;
+ if (rr >= 5 && rr <= 94) {
+ blockOffset = rr - 5;
+ volume = true;
+ } else if (rr >= 99 && rr <= 188) {
+ blockOffset = rr - 99;
+ volume = false;
+ }
+ if (blockOffset < 0 || blockOffset % 5 == 0) continue;
+ int k = blockOffset % 5;
+ String area = areas.get(blockOffset / 5);
+ double v = 0.0, lv = 0.0;
+ for (int m = 1; m <= months; m++) {
+ if (k <= 2) {
+ v += midClassVal(mid, year, m, area, k, volume);
+ lv += midClassVal(mid, year - 1, m, area, k, volume);
+ }
+ }
+ Row row = sheet.getRow(r0);
+ if (row == null) continue;
+ Cell c = row.getCell(colIdx);
+ if (c == null) c = row.createCell(colIdx);
+ c.setBlank();
+ if (v != 0.0 && lv != 0.0) c.setCellValue(round((v - lv) / lv, 4));
+ }
+ }
+
+ /** 璐ц繍鍒嗗競宸炴槑缁嗚濉厖锛�1..fillMonths 鏈堝��/鍚屾瘮锛堟渶澶� 12 鏈堬紝鍏朵綑娓呯┖锛�+ 绱/绱鍚屾瘮锛坈umCol 璧蜂袱鍒楋級 */
+ private void fillFreightDetailRow(Row row, int fillMonths, int cumCol,
+ java.util.function.IntFunction<Double> monthValue,
+ java.util.function.IntFunction<Double> monthYoy,
+ Double cumValue, Double cumYoy) {
+ for (int m = 1; m <= (fillMonths > 6 ? 12 : 6); m++) {
+ if (m <= fillMonths) {
+ setFreightCell(row, 2 + (m - 1) * 2, monthValue.apply(m));
+ setFreightCell(row, 3 + (m - 1) * 2, monthYoy.apply(m));
+ } else {
+ setFreightCell(row, 2 + (m - 1) * 2, (Double) null);
+ setFreightCell(row, 3 + (m - 1) * 2, (Double) null);
+ }
+ }
+ setFreightCell(row, cumCol, cumValue);
+ setFreightCell(row, cumCol + 1, cumYoy);
+ }
+
+ /** H2032 瑙勪笂鏌愭湀鍚堣锛堝惃鈫掍竾鍚級锛涙棤璇ユ湀鏁版嵁杩斿洖 null */
+ private Double monthFreightWan(Map<String, Map<Integer, Double>> byCityMonth, String city, int month) {
+ Map<Integer, Double> byMonth = byCityMonth == null ? null : byCityMonth.get(city);
+ Double v = byMonth == null ? null : byMonth.get(month);
+ return v == null ? null : round(v / 10000.0, 4);
+ }
+
+ /** 鍚屾瘮 = (鏈湡-鍩烘湡)/鍩烘湡锛涗换涓�鏈熺己澶辨垨鍩烘湡涓� 0 杩斿洖 null */
+ private Double growthYoy(Double cur, Double last) {
+ if (cur == null || last == null || last == 0.0) return null;
+ return (cur - last) / last;
+ }
+
+ /** 鎺掑悕琛ㄧ浜岄〉鍒楀ご銆岀疮璁″畬鎴愩�嶁啋銆屽綋鏈堝畬鎴愩�嶏紙浠呭鍑哄唴瀛樻浛鎹紝妯℃澘鏂囦欢涓嶆敼锛� */
+ private void renameRankMonthHeader(Sheet sheet, int headerRowIdx) {
+ Row row = sheet.getRow(headerRowIdx);
+ if (row == null) return;
+ for (int col : new int[]{1, 6, 11}) {
+ Cell c = row.getCell(col);
+ if (c == null || c.getCellType() != CellType.STRING) continue;
+ String s = c.getStringCellValue();
+ if (s != null && s.contains("绱瀹屾垚")) c.setCellValue(s.replace("绱瀹屾垚", "褰撴湀瀹屾垚"));
+ }
+ }
+
+ /** 璐ц繍閲忔帓鍚嶅潡濉厖锛氭ā鏉� 1-based r4 璧凤紙鍏ㄧ渷+17甯傚窞锛夛紝Q/R 鍗犳瘮鍏紡淇濈暀涓嶅姩 */
+ private void fillFreightRankBlock(Sheet sheet, int start,
+ Map<String, Double> above, Map<String, Double> below, Map<String, Double> total,
+ Map<String, Double> aboveYoy, Map<String, Double> belowYoy, Map<String, Double> totalYoy,
+ Double provAbove, Double provBelow, Double provTotal,
+ Double provAboveYoy, Double provBelowYoy, Double provTotalYoy) {
+ Row provRow = sheet.getRow(start);
+ if (provRow == null) provRow = sheet.createRow(start);
+ setFreightCell(provRow, 1, provAbove);
+ setFreightCell(provRow, 4, provAboveYoy);
+ setFreightCell(provRow, 6, provBelow);
+ setFreightCell(provRow, 9, provBelowYoy);
+ setFreightCell(provRow, 11, provTotal);
+ setFreightCell(provRow, 14, provTotalYoy);
+ int rowIdx = start + 1;
+ for (String city : RegionUtil.cityList()) {
+ Row row = sheet.getRow(rowIdx);
+ if (row == null) row = sheet.createRow(rowIdx);
+ setFreightCell(row, 1, above.get(city));
+ setFreightCell(row, 2, rankOfMap(above, city));
+ setFreightCell(row, 3, ratioOf(above.get(city), provAbove));
+ setFreightCell(row, 4, aboveYoy.get(city));
+ setFreightCell(row, 5, yoyRankOfMap(aboveYoy, city));
+ setFreightCell(row, 6, below.get(city));
+ setFreightCell(row, 7, rankOfMap(below, city));
+ setFreightCell(row, 8, ratioOf(below.get(city), provBelow));
+ setFreightCell(row, 9, belowYoy.get(city));
+ setFreightCell(row, 10, yoyRankOfMap(belowYoy, city));
+ setFreightCell(row, 11, total.get(city));
+ setFreightCell(row, 12, rankOfMap(total, city));
+ setFreightCell(row, 13, ratioOf(total.get(city), provTotal));
+ setFreightCell(row, 14, totalYoy.get(city));
+ setFreightCell(row, 15, yoyRankOfMap(totalYoy, city));
+ rowIdx++;
+ }
+ }
+
+ /** 鍛ㄨ浆閲忔帓鍚嶅潡濉厖锛氭ā鏉� 1-based r4 璧凤紙鍏ㄧ渷+17甯傚窞锛� */
+ private void fillTurnoverRankBlock(Sheet sheet, int start,
+ Map<String, ScaleSplitTransport> cumMap, ScaleSplitTransport province) {
+ if (province == null) province = new ScaleSplitTransport();
+ Double provAbove = province.getAboveScaleTurnover();
+ Double provBelow = province.getBelowScaleTurnover();
+ Double provTotal = province.getTotalTurnover();
+ Row provRow = sheet.getRow(start);
+ if (provRow == null) provRow = sheet.createRow(start);
+ setFreightCell(provRow, 1, provAbove);
+ setFreightCell(provRow, 4, province.getAboveScaleYoy());
+ setFreightCell(provRow, 6, provBelow);
+ setFreightCell(provRow, 9, province.getBelowScaleYoy());
+ setFreightCell(provRow, 11, provTotal);
+ setFreightCell(provRow, 14, province.getTotalYoy());
+ setFreightShare(provRow, provAbove, provTotal);
+ int rowIdx = start + 1;
+ for (String city : RegionUtil.cityList()) {
+ Row row = sheet.getRow(rowIdx);
+ if (row == null) row = sheet.createRow(rowIdx);
+ ScaleSplitTransport cum = cumMap.get(city);
+ Double above = cum == null ? null : cum.getAboveScaleTurnover();
+ Double below = cum == null ? null : cum.getBelowScaleTurnover();
+ Double total = cum == null ? null : cum.getTotalTurnover();
+ setFreightCell(row, 1, above);
+ setFreightCell(row, 2, cum == null ? null : rankOfTurnover(cumMap, city, 0));
+ setFreightCell(row, 3, ratioOf(above, provAbove));
+ setFreightCell(row, 4, cum == null ? null : cum.getAboveScaleYoy());
+ setFreightCell(row, 5, cum == null ? null : yoyRankOfTurnover(cumMap, city, 0));
+ setFreightCell(row, 6, below);
+ setFreightCell(row, 7, cum == null ? null : rankOfTurnover(cumMap, city, 1));
+ setFreightCell(row, 8, ratioOf(below, provBelow));
+ setFreightCell(row, 9, cum == null ? null : cum.getBelowScaleYoy());
+ setFreightCell(row, 10, cum == null ? null : yoyRankOfTurnover(cumMap, city, 1));
+ setFreightCell(row, 11, total);
+ setFreightCell(row, 12, cum == null ? null : rankOfTurnover(cumMap, city, 2));
+ setFreightCell(row, 13, ratioOf(total, provTotal));
+ setFreightCell(row, 14, cum == null ? null : cum.getTotalYoy());
+ setFreightCell(row, 15, cum == null ? null : yoyRankOfTurnover(cumMap, city, 2));
+ setFreightShare(row, above, total);
+ rowIdx++;
+ }
+ }
+
+ /** 鍛ㄨ浆閲忔帓鍚� Q/R 鍗犳瘮锛氭ā鏉夸负缂撳瓨鍊硷紝鎸夋柊鏁版嵁閲嶇畻锛堣涓婂崰姣� 1 浣嶅皬鏁帮級 */
+ private void setFreightShare(Row row, Double above, Double total) {
+ if (total != null && total > 0 && above != null) {
+ double share = round(above * 10.0 / total, 1);
+ setFreightCell(row, 16, share);
+ setFreightCell(row, 17, round(10.0 - share, 1));
+ } else {
+ setFreightCell(row, 16, (Double) null);
+ setFreightCell(row, 17, (Double) null);
+ }
+ }
+
// ==================== 鏁版嵁鍔犺浇 ====================
/** 褰撴湀鏁版嵁: city -> month -> record锛堜笉鍚叏鐪侊級 */
@@ -306,9 +1329,12 @@
/** H2032瑙勪笂: city -> month -> 璐ц繍閲�(鍚�) */
private Map<String, Map<Integer, Double>> loadH2032FreightByMonth(String period) {
Map<String, Map<Integer, Double>> result = new HashMap<>();
+ String yearPrefix = period.length() >= 4 ? period.substring(0, 4) : null;
List<H2032EnterpriseMonthly> list = h2032Mapper.selectList(null);
for (H2032EnterpriseMonthly record : list) {
if (record.getReportPeriod() == null || record.getReportPeriod().compareTo(period) > 0) continue;
+ // H2032 琛ㄥ悓鏃跺瓨鏈夊線骞存湀鎶ワ紝缁熻褰撳勾瑙勪笂鍊兼椂鍙彇涓庢姤琛ㄦ湡鍚屽勾鐨勮褰曪紝閬垮厤鍘诲勾鏁版嵁鍙犲姞
+ if (yearPrefix != null && !record.getReportPeriod().startsWith(yearPrefix)) continue;
String city = RegionUtil.cityByCode(record.getRegionCode());
if (city == null) continue;
int month = parseMonth(record.getReportPeriod());
@@ -321,9 +1347,11 @@
/** H2032瑙勪笂绱: city -> 璐ц繍閲�(鍚�) */
private Map<String, Double> loadH2032FreightCumulative(String period) {
Map<String, Double> result = new HashMap<>();
+ String yearPrefix = period.length() >= 4 ? period.substring(0, 4) : null;
List<H2032EnterpriseMonthly> list = h2032Mapper.selectList(null);
for (H2032EnterpriseMonthly record : list) {
if (record.getReportPeriod() == null || record.getReportPeriod().compareTo(period) > 0) continue;
+ if (yearPrefix != null && !record.getReportPeriod().startsWith(yearPrefix)) continue;
String city = RegionUtil.cityByCode(record.getRegionCode());
if (city == null) continue;
double freight = record.getFreightTotal() == null ? 0.0 : record.getFreightTotal();
@@ -771,10 +1799,915 @@
return rank;
}
+ // ==================== 4. 鐢熸垚_鍏矾鏃呭鍒嗗競宸炴槑缁�.xlsx锛堟湀鎶�/骞存姤锛� ====================
+
+ /**
+ * 鍏矾鏃呭鍒嗗競宸炴槑缁�
+ * @param period 鏈堟姤: 2026-06锛堜粖骞�1-6鏈堬級锛涘勾鎶�: 2026锛堝叏骞�12涓湀锛�
+ * @param mode month/year
+ */
+ /**
+ * 鐢熸垚_鍏矾鏃呭鍒嗗競宸�.xlsx锛氫互 docs/鍏矾鏃呭+鑳借��/杈撳嚭 妯℃澘涓哄簳绋匡紝
+ * 淇濈暀琛ㄥご/鍚堝苟/鍒楀/鍏紡/鏍峰紡锛屼粎鏇挎崲 2026 骞� 1..6 鏈堟湀搴﹀垪鏁版嵁锛堝杩愰噺/鍛ㄨ浆閲�/涓綋琛岋級銆�
+ * 2025/2024 鍘嗗彶鍒椾繚鐣欐ā鏉垮�硷紱绱/鍚屾瘮/鍏ㄧ渷琛屽叕寮忎繚鐣欏苟閲嶇畻銆�
+ */
+ public byte[] exportPassengerCityDetail(String period, String mode) throws Exception {
+ int maxMonth = monthOf(period, mode);
+ int currentYear = Integer.parseInt(period.substring(0, 4));
+ File template = resolvePassengerTemplate("鐢熸垚_鍏矾鏃呭鍒嗗競宸�.xlsx");
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ fixPassengerHeaderYear(sheet, currentYear); // 琛ㄥご骞翠唤鍔ㄦ�佸寲锛堜笉鍐欐 2026锛�
+ Map<Integer, Map<String, PassengerAgg>> data = loadPassengerAggMap();
+ Map<Integer, Map<String, double[]>> indi = loadPassengerIndividualMap();
+ int fillMonths = maxMonth; // 1..N 鏈堬紙N>6 鏃舵ā鏉胯嚜鍔ㄥ悜鍙虫墿鍒楀埌 12 鏈堬級
+ boolean extended = fillMonths > 6;
+ if (extended) extendMonthlyColumns(sheet, 1, currentYear, 3, sheet.getLastRowNum());
+ String currentRegion = null;
+ for (int r = 3; r <= sheet.getLastRowNum(); r++) { // 浠� R4 璧凤細A 鍒楀悎骞惰鏄尯鍩熸爣璁帮紙R4 鍏ㄧ渷銆丷8 姝︽眽甯傗�︼級
+ Row row = sheet.getRow(r);
+ if (row == null) continue;
+ Cell nameCell = row.getCell(0);
+ Cell metricCell = row.getCell(1);
+ if (metricCell == null) continue;
+ String areaName = cellText(nameCell);
+ if (areaName != null && !areaName.trim().isEmpty()) {
+ currentRegion = "鍏ㄧ渷".equals(areaName.trim()) ? "婀栧寳鐪�" : RegionUtil.normalizeCityName(areaName.trim());
+ }
+ if (currentRegion == null) continue;
+ String metric = cellText(metricCell);
+ if (metric == null) continue;
+ int metricIdx = cityMetricIndexOf(metric);
+ if (metricIdx < 0) continue;
+ String region = currentRegion;
+ for (int m = 1; m <= fillMonths; m++) {
+ int col = 2 + (m - 1) * 2; // C,E,G,I,K,M,O,Q,S,U,W,Y锛�7-12 鏈堜负鎵╁垪鍒楋級
+ Cell c = row.getCell(col);
+ boolean keepFormula = c != null && c.getCellType() == CellType.FORMULA; // 鍏ㄧ渷/绱绛夊叕寮忎繚鐣�
+ double v = passengerMonthVal(data, indi, currentYear, m, region, metricIdx);
+ if (!keepFormula) {
+ if (c == null) c = row.createCell(col);
+ if (v == 0.0) c.setBlank(); else c.setCellValue(round(v, 4));
+ }
+ // 鍚屾瘮鍒楋細搴撳唴鍘诲勾鍚屾湀鍚屾瘮锛堟ā鏉� #REF! 鍏紡鏇挎崲涓烘暟鍊硷紝鍏紡琛屼篃瑕嗗啓锛�
+ double lv = passengerMonthVal(data, indi, currentYear - 1, m, region, metricIdx);
+ Cell yc = row.getCell(col + 1);
+ if (yc == null) yc = row.createCell(col + 1);
+ if (v == 0.0 || lv == 0.0) yc.setBlank(); else yc.setCellValue(round((v - lv) / lv, 4));
+ }
+ // 绱鍚屾瘮鍒楋紙妯℃澘 #REF! 鈫� 搴撳唴鍘诲勾 1..N 鏈堢疮璁″悓姣旀暟鍊硷級
+ int cumCol = extended ? 26 : 14;
+ Double cumYoy = passengerCumYoy(data, indi, currentYear, fillMonths, region, metricIdx);
+ Cell yc2 = row.getCell(cumCol + 1);
+ if (yc2 == null) yc2 = row.createCell(cumCol + 1);
+ if (cumYoy == null) yc2.setBlank(); else yc2.setCellValue(round(cumYoy, 4));
+ }
+ recalc(wb);
+ return toBytes(wb);
+ }
+ }
+
+ /** 鍒嗗競宸炶〃鎸囨爣琛岋細0=瀹㈣繍閲� 1=鍛ㄨ浆閲� 2=涓綋瀹㈣繍閲� 3=涓綋鍛ㄨ浆閲忥紱鏃犳硶璇嗗埆杩斿洖 -1 */
+ private int cityMetricIndexOf(String metric) {
+ if (metric == null) return -1;
+ boolean indi = metric.contains("涓綋");
+ if (metric.contains("瀹㈣繍閲�")) return indi ? 2 : 0;
+ if (metric.contains("鍛ㄨ浆閲�")) return indi ? 3 : 1;
+ return -1;
+ }
+
+ private String cellText(Cell c) {
+ if (c == null) return null;
+ if (c.getCellType() == CellType.STRING) return c.getStringCellValue();
+ if (c.getCellType() == CellType.NUMERIC) return String.valueOf(c.getNumericCellValue());
+ return null;
+ }
+
+ /** 涓綋瀹㈣繍閲�/鍛ㄨ浆閲忥紙涓囦汉/涓囦汉鍏噷锛� */
+ private double individualVal(Map<Integer, Map<String, double[]>> indi, int year, int month, String region, int idx) {
+ Map<String, double[]> mm = indi.get(year * 100 + month);
+ if (mm == null) return 0;
+ double[] arr = mm.get(region);
+ if (arr == null) return 0;
+ return idx < arr.length ? arr[idx] : 0;
+ }
+
+ /** 涓綋瀹㈣繍閲�/鍛ㄨ浆閲忔暟鎹細骞�*100+鏈� -> (甯傚窞/鍏ㄧ渷 -> [涓綋瀹㈣繍閲�(涓囦汉), 涓綋鍛ㄨ浆閲�(涓囦汉鍏噷)]) */
+ private Map<Integer, Map<String, double[]>> loadPassengerIndividualMap() {
+ Map<Integer, Map<String, double[]>> data = new HashMap<>();
+ for (PassengerIndividualMonthly e : passengerIndividualMapper.selectList(null)) {
+ if (e.getReportPeriod() == null) continue;
+ String[] parts = e.getReportPeriod().split("-");
+ if (parts.length != 2) continue;
+ int y, m;
+ try {
+ y = Integer.parseInt(parts[0]);
+ m = Integer.parseInt(parts[1]);
+ } catch (NumberFormatException ex) {
+ continue;
+ }
+ String city = RegionUtil.cityByCode(e.getRegionCode());
+ if (city == null) continue;
+ int key = y * 100 + m;
+ double pass = nz(e.getPassengerCount()) / 10000.0;
+ double turn = nz(e.getTurnover()) / 10000.0;
+ double[] arr = data.computeIfAbsent(key, k -> new HashMap<>()).computeIfAbsent(city, k -> new double[2]);
+ arr[0] += pass;
+ arr[1] += turn;
+ double[] prov = data.get(key).computeIfAbsent("婀栧寳鐪�", k -> new double[2]);
+ prov[0] += pass;
+ prov[1] += turn;
+ }
+ return data;
+ }
+
+ private PassengerAgg aggOf(Map<Integer, Map<String, PassengerAgg>> data, int year, int month, String region) {
+ Map<String, PassengerAgg> monthMap = data.get(year * 100 + month);
+ return monthMap == null ? null : monthMap.get(region);
+ }
+
+ private Double cumOf(Map<Integer, Map<String, PassengerAgg>> data, int year, String region, int monthCount, int metricIdx) {
+ double sum = 0.0;
+ boolean has = false;
+ for (int m = 1; m <= monthCount; m++) {
+ Double v = metricValue(aggOf(data, year, m, region), metricIdx);
+ if (v != null) {
+ sum += v;
+ has = true;
+ }
+ }
+ return has ? sum : null;
+ }
+
+ private Double yoy(Double cur, Double base) {
+ if (cur == null || base == null || base == 0.0) return null;
+ return round((cur - base) / base, 4);
+ }
+
+ /** 鎸囨爣鍙栧�硷紙宸叉崲绠椾负涓囦汉/涓囦汉鍏噷/鍏噷锛涙棤鏁版嵁杩斿洖 null锛� */
+ private Double metricValue(PassengerAgg agg, int metric) {
+ if (agg == null) return null;
+ switch (metric) {
+ case 0: return agg.passengerTotal / 10000.0;
+ case 1: return agg.passengerTotal / 10000.0;
+ case 2: return agg.passengerClass1 / 10000.0;
+ case 3: return agg.passengerClass2 / 10000.0;
+ case 4: return agg.passengerClass3 / 10000.0;
+ case 5: return agg.passengerClass4 / 10000.0;
+ case 6: return agg.passengerCharter / 10000.0;
+ case 7:
+ case 8:
+ case 9: return null; // 鍩庡競瀹㈣繍妯″潡鏁版嵁锛屾殏鐣欑┖
+ case 10: return agg.turnoverTotal / 10000.0;
+ case 11: return agg.turnoverClass1 / 10000.0;
+ case 12: return agg.turnoverClass2 / 10000.0;
+ case 13: return agg.turnoverClass3 / 10000.0;
+ case 14: return agg.turnoverClass4 / 10000.0;
+ case 15: return agg.turnoverCharter / 10000.0;
+ case 16: return ratioOrNull(agg.turnoverTotal, agg.passengerTotal);
+ case 17: return ratioOrNull(agg.turnoverClass1, agg.passengerClass1);
+ case 18: return ratioOrNull(agg.turnoverClass2, agg.passengerClass2);
+ case 19: return ratioOrNull(agg.turnoverClass3, agg.passengerClass3);
+ case 20: return ratioOrNull(agg.turnoverClass4, agg.passengerClass4);
+ case 21: return ratioOrNull(agg.turnoverCharter, agg.passengerCharter);
+ default: return null;
+ }
+ }
+
+ private Double ratioOrNull(double numerator, double denominator) {
+ if (denominator == 0.0) return null;
+ return numerator / denominator;
+ }
+
+ /** 鍗曟湀鍏ㄥ競宸炰紒涓氭眹鎬� */
+ private static class PassengerAgg {
+ double passengerTotal;
+ double passengerClass1;
+ double passengerClass2;
+ double passengerClass3;
+ double passengerClass4;
+ double passengerCharter;
+ double turnoverTotal;
+ double turnoverClass1;
+ double turnoverClass2;
+ double turnoverClass3;
+ double turnoverClass4;
+ double turnoverCharter;
+
+ void add(PassengerEnterpriseMonthly e) {
+ passengerTotal += nz(e.getPassengerClass1()) + nz(e.getPassengerClass2()) + nz(e.getPassengerClass3())
+ + nz(e.getPassengerClass4()) + nz(e.getPassengerCharter());
+ passengerClass1 += nz(e.getPassengerClass1());
+ passengerClass2 += nz(e.getPassengerClass2());
+ passengerClass3 += nz(e.getPassengerClass3());
+ passengerClass4 += nz(e.getPassengerClass4());
+ passengerCharter += nz(e.getPassengerCharter());
+ turnoverTotal += nz(e.getTurnoverClass1()) + nz(e.getTurnoverClass2()) + nz(e.getTurnoverClass3())
+ + nz(e.getTurnoverClass4()) + nz(e.getTurnoverCharter());
+ turnoverClass1 += nz(e.getTurnoverClass1());
+ turnoverClass2 += nz(e.getTurnoverClass2());
+ turnoverClass3 += nz(e.getTurnoverClass3());
+ turnoverClass4 += nz(e.getTurnoverClass4());
+ turnoverCharter += nz(e.getTurnoverCharter());
+ }
+
+ private double nz(Double v) {
+ return v == null ? 0.0 : v;
+ }
+ }
+
+
+
+ // ==================== 涓彛寰勬槑缁�/鎺掑悕/鍒嗘瀽锛圚203-1 鍏矾鏃呭锛� ====================
+
+ /** 鍔犺浇 骞�*100+鏈� -> (甯傚窞/鍏ㄧ渷 -> 浼佷笟姹囨��) 鏁版嵁 */
+ private Map<Integer, Map<String, PassengerAgg>> loadPassengerAggMap() {
+ Map<Integer, Map<String, PassengerAgg>> data = new HashMap<>();
+ List<PassengerEnterpriseMonthly> list = passengerMapper.selectList(null);
+ for (PassengerEnterpriseMonthly e : list) {
+ if (e.getReportPeriod() == null) continue;
+ String[] parts = e.getReportPeriod().split("-");
+ if (parts.length != 2) continue;
+ int y;
+ int m;
+ try {
+ y = Integer.parseInt(parts[0]);
+ m = Integer.parseInt(parts[1]);
+ } catch (NumberFormatException ex) {
+ continue;
+ }
+ String city = RegionUtil.cityByCode(e.getRegionCode());
+ if (city == null) continue;
+ int key = y * 100 + m;
+ Map<String, PassengerAgg> monthMap = data.computeIfAbsent(key, k -> new HashMap<>());
+ monthMap.computeIfAbsent(city, k -> new PassengerAgg()).add(e);
+ monthMap.computeIfAbsent("婀栧寳鐪�", k -> new PassengerAgg()).add(e);
+ }
+ return data;
+ }
+
+ /**
+ * 涓彛寰勬槑缁嗭細瀹㈣繍閲忓潡 + 鏃呭鍛ㄨ浆閲忓潡锛堟��/鍏矾鐝嚎/鍩庨檯鍩庝埂鍏氦/宸℃父鍑虹/缃戠害杞︼級
+ */
+ /**
+ * 鐢熸垚_涓彛寰勬槑缁�.xlsx锛氫互鏍蜂緥涓哄簳绋裤�傛暟鎹尯澶栭儴寮曠敤鍏紡锛堢彮绾�/鍏氦/鍑虹/缃戠害杞︼級鏇挎崲涓哄簱鍐呮暟鍊硷紝
+ * 2025 骞村垪淇濈暀妯℃澘缂撳瓨鍊硷紙鍘诲勾鏁版嵁锛夛紝鍐呴儴鍏紡锛堢疮璁�/鍚屾瘮/姹傚拰锛変繚鐣欏苟閲嶇畻銆�
+ */
+ public byte[] exportPassengerMidDetail(String period, String mode) throws Exception {
+ int maxMonth = monthOf(period, mode);
+ int currentYear = Integer.parseInt(period.substring(0, 4));
+ File template = resolvePassengerTemplate("鐢熸垚_涓彛寰勬槑缁�.xlsx");
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ fixPassengerHeaderYear(sheet, currentYear); // 琛ㄥご骞翠唤鍔ㄦ�佸寲锛堜笉鍐欐 2026锛�
+ Map<Integer, Map<String, double[][]>> mid = loadMidClassMap();
+ int fillMonths = maxMonth; // 1..N 鏈堬紙N>6 鏃舵ā鏉胯嚜鍔ㄥ悜鍙虫墿鍒楀埌 12 鏈堬級
+ boolean extended = fillMonths > 6;
+ if (extended) extendMonthlyColumns(sheet, 2, currentYear, 4, sheet.getLastRowNum());
+ List<String> areas = midTemplateAreas();
+ for (Row row : sheet) {
+ if (row == null) continue;
+ for (Cell c : row) {
+ if (c.getCellType() != CellType.FORMULA) continue;
+ String f = c.getCellFormula();
+ if (f == null) continue;
+ boolean crossBook = f.contains("[");
+ if (!crossBook && !isYoyMonthCol(c.getColumnIndex() + 1)) continue; // 鍐呴儴鍏紡锛堝悎璁�/绱锛変繚鐣欓噸绠楋紱鍚屾瘮鍒� #REF! 瑕嗗啓涓烘暟鍊�
+ if (crossBook && !is2026MonthCol(c.getColumnIndex() + 1)) {
+ keepCached(c); // 2025 骞村垪淇濈暀妯℃澘缂撳瓨鍊�
+ continue;
+ }
+ int r = c.getRowIndex() + 1;
+ int col = c.getColumnIndex() + 1;
+ int blockOffset = -1;
+ boolean volume = false;
+ if (r >= 5 && r <= 94) {
+ blockOffset = r - 5;
+ volume = true;
+ } else if (r >= 99 && r <= 188) {
+ blockOffset = r - 99;
+ volume = false;
+ }
+ if (blockOffset < 0) {
+ keepCached(c); // r1/r2 澶囨敞绛�
+ continue;
+ }
+ if (blockOffset % 5 == 0) {
+ if (isYoyMonthCol(col)) {
+ fillMidYoyCell(c, mid, currentYear, monthOfCol(col), areas.get(blockOffset / 5), -1, volume);
+ } else {
+ keepCached(c); // 鎬昏鍐呴儴鍏紡锛堥槻寰★級
+ }
+ continue;
+ }
+ int k = blockOffset % 5; // 1=鐝嚎 2=鍏氦 3=鍑虹 4=缃戠害杞�
+ String area = areas.get(blockOffset / 5);
+ if (is2026MonthCol(col)) {
+ fillMidCell(c, mid, currentYear, monthOfCol(col), area, k, volume);
+ } else if (isYoyMonthCol(col)) {
+ fillMidYoyCell(c, mid, currentYear, monthOfCol(col), area, k, volume);
+ } else {
+ keepCached(c); // 2025 骞村垪淇濈暀妯℃澘缂撳瓨鍊�
+ }
+ }
+ }
+ // 绱鍚屾瘮鍒楋紙妯℃澘 #REF! 鈫� 搴撳唴鍘诲勾 1..N 鏈堢疮璁″悓姣旀暟鍊硷級
+ fillMidCumYoyColumn(sheet, mid, currentYear, fillMonths, extended ? 27 : 15);
+ recalc(wb);
+ clearFormulaErrorsAll(wb); // 鍘诲勾鍚屾湡鏄庣粏椤垫畫鐣� #REF! 鍚屾瘮鍏紡 鈫� 娓呯┖
+ return toBytes(wb);
+ }
+ }
+
+ /** 涓彛寰勬槑缁嗘ā鏉垮湴鍖洪『搴忥紙涓� RegionUtil.CITY_LIST 涓�鑷达細姝︽眽甯傗�︾鍐滄灦鏋楀尯锛� */
+ private List<String> midTemplateAreas() {
+ List<String> areas = new java.util.ArrayList<>();
+ areas.add("婀栧寳鐪�");
+ areas.addAll(RegionUtil.CITY_LIST);
+ return areas;
+ }
+
+ private boolean is2026MonthCol(int col) {
+ return col >= 3 && col <= 25 && col % 2 == 1;
+ }
+
+ /** 鏈堝悓姣斿垪锛�1-based 鍋舵暟鍒� 4..26锛� */
+ private boolean isYoyMonthCol(int col) {
+ return col >= 4 && col <= 26 && col % 2 == 0;
+ }
+
+ private int monthOfCol(int col) {
+ return (col - 1) / 2;
+ }
+
+ /** 濉腑鍙e緞鏁版嵁鍗曞厓鏍硷細鍑虹/缃戠害杞�(3/4)鏄惧紡 0锛岀彮绾�/鍏氦濉簱鍐呭�硷紙鏃犲�兼竻绌猴級 */
+ private void fillMidCell(Cell c, Map<Integer, Map<String, double[][]>> mid, int year, int month, String area, int k, boolean volume) {
+ if (k == 3 || k == 4) {
+ writeExplicitZero(c); // 鍑虹/缃戠害杞︽殏鏃犳暟鎹簮锛屾樉寮� 0
+ return;
+ }
+ double v = midClassVal(mid, year, month, area, k, volume);
+ // POI setCellValue(double) 瀵瑰叕寮忓崟鍏冩牸鍙洿鏂扮紦瀛樹笉绉婚櫎鍏紡锛屽繀椤诲厛 setBlank 鍐嶅啓鍊�
+ c.setBlank();
+ if (v != 0.0) c.setCellValue(round(v, 4));
+ }
+
+ /** 鏄惧紡鍐欏叆 0锛圥OI setCellValue(0.0) 浼氳浆 blank锛岄渶鎿嶄綔搴曞眰 XML锛� */
+ private void writeExplicitZero(Cell c) {
+ c.setBlank();
+ if (c instanceof XSSFCell) {
+ try {
+ ((XSSFCell) c).getCTCell().setT(STCellType.N);
+ ((XSSFCell) c).getCTCell().setV("0");
+ } catch (Exception e) {
+ log.warn("writeExplicitZero failed: {}", e.getMessage());
+ }
+ }
+ }
+
+ private double midClassVal(Map<Integer, Map<String, double[][]>> mid, int year, int month, String area, int k, boolean volume) {
+ Map<String, double[][]> mm = mid.get(year * 100 + month);
+ if (mm == null) return 0;
+ double[][] arr = mm.get(area);
+ if (arr == null) return 0;
+ if (k < 0 || k >= arr.length) return 0;
+ return volume ? arr[k][0] : arr[k][1];
+ }
+
+ /** 鍏紡鍗曞厓鏍兼浛鎹负缂撳瓨鏁板�硷紙閬垮厤璺ㄧ翱寮曠敤鏂摼锛涢潪鏁板�肩紦瀛樼疆绌猴級 */
+ private void keepCached(Cell c) {
+ try {
+ double v = 0.0;
+ boolean has = false;
+ if (c.getCachedFormulaResultType() == CellType.NUMERIC) {
+ v = c.getNumericCellValue();
+ has = true;
+ }
+ c.setBlank();
+ if (has && v != 0.0) c.setCellValue(v);
+ } catch (Exception e) {
+ try { c.setBlank(); } catch (Exception ignore) { }
+ }
+ }
+
+ /**
+ * 涓彛寰勫垎绫绘湀搴︽暟鎹細骞�*100+鏈� -> (甯傚窞/鍏ㄧ渷 -> double[5][2])
+ * 缁村害 0=鎬婚噺 1=鍏矾鐝嚎(h2031+涓綋) 2=鍩庨檯鍩庝埂鍏氦(cityBus) 3=宸℃父鍑虹 4=缃戠害杞︼紱[瀹㈣繍閲�(涓囦汉), 鍛ㄨ浆閲�(涓囦汉鍏噷)]
+ */
+ private Map<Integer, Map<String, double[][]>> loadMidClassMap() {
+ Map<Integer, Map<String, double[][]>> mid = new HashMap<>();
+ for (PassengerEnterpriseMonthly e : passengerMapper.selectList(null)) {
+ if (e.getReportPeriod() == null) continue;
+ String[] parts = e.getReportPeriod().split("-");
+ if (parts.length != 2) continue;
+ int y, m;
+ try {
+ y = Integer.parseInt(parts[0]);
+ m = Integer.parseInt(parts[1]);
+ } catch (NumberFormatException ex) {
+ continue;
+ }
+ String city = RegionUtil.cityByCode(e.getRegionCode());
+ if (city == null) continue;
+ int key = y * 100 + m;
+ double pass = (nz(e.getPassengerClass1()) + nz(e.getPassengerClass2()) + nz(e.getPassengerClass3())
+ + nz(e.getPassengerClass4()) + nz(e.getPassengerCharter())) / 10000.0;
+ double turn = (nz(e.getTurnoverClass1()) + nz(e.getTurnoverClass2()) + nz(e.getTurnoverClass3())
+ + nz(e.getTurnoverClass4()) + nz(e.getTurnoverCharter())) / 10000.0;
+ addMidClass(mid, key, city, 1, pass, turn);
+ addMidClass(mid, key, "婀栧寳鐪�", 1, pass, turn);
+ }
+ for (PassengerIndividualMonthly e : passengerIndividualMapper.selectList(null)) { // 涓綋骞跺叆鍏矾鐝嚎/鎬婚噺锛�09-03 鍙e緞锛�
+ if (e.getReportPeriod() == null) continue;
+ String[] parts = e.getReportPeriod().split("-");
+ if (parts.length != 2) continue;
+ int y, m;
+ try {
+ y = Integer.parseInt(parts[0]);
+ m = Integer.parseInt(parts[1]);
+ } catch (NumberFormatException ex) {
+ continue;
+ }
+ String city = RegionUtil.cityByCode(e.getRegionCode());
+ if (city == null) continue;
+ int key = y * 100 + m;
+ double pass = nz(e.getPassengerCount()) / 10000.0;
+ double turn = nz(e.getTurnover()) / 10000.0;
+ addMidClass(mid, key, city, 1, pass, turn);
+ addMidClass(mid, key, "婀栧寳鐪�", 1, pass, turn);
+ }
+ for (CityBusMonthly b : cityBusMapper.selectList(null)) {
+ if (b.getReportPeriod() == null || b.getCity() == null) continue;
+ String[] parts = b.getReportPeriod().split("-");
+ if (parts.length != 2) continue;
+ int y, m;
+ try {
+ y = Integer.parseInt(parts[0]);
+ m = Integer.parseInt(parts[1]);
+ } catch (NumberFormatException ex) {
+ continue;
+ }
+ String city = RegionUtil.normalizeCityName(b.getCity());
+ if (city == null) continue;
+ int key = y * 100 + m;
+ addMidClass(mid, key, city, 2, nz(b.getPassengerChengxiang()), nz(b.getTurnoverChengxiang()));
+ addMidClass(mid, key, "婀栧寳鐪�", 2, nz(b.getPassengerChengxiang()), nz(b.getTurnoverChengxiang()));
+ }
+ return mid;
+ }
+
+ /** 鍐欏叆鍒嗙被鍊煎苟绱姞鎬婚噺锛堢淮搴�0锛� */
+ private void addMidClass(Map<Integer, Map<String, double[][]>> mid, int key, String city, int k, double pass, double turn) {
+ double[][] arr = mid.computeIfAbsent(key, kk -> new HashMap<>()).computeIfAbsent(city, kk -> new double[5][2]);
+ arr[k][0] += pass;
+ arr[k][1] += turn;
+ arr[0][0] += pass;
+ arr[0][1] += turn;
+ }
+
+ private int writeMidBlock(Sheet sheet, Map<Integer, Map<String, PassengerAgg>> data, int[] years,
+ int currentYear, int maxMonth, int startRow, String title, boolean volume) {
+ Row titleRow = sheet.createRow(startRow);
+ titleRow.createCell(0).setCellValue(title);
+ Row noteRow = sheet.createRow(startRow + 1);
+ noteRow.createCell(0).setCellValue("娉細涓彛寰勭敱鍏矾鐝嚎銆佸煄闄呭煄涔″叕浜ゃ�佸煄闄呭煄涔″嚭绉熴�佸煄闄呭煄涔$綉绾﹁溅鍥涢儴鍒嗘瀯鎴�");
+ Row header = sheet.createRow(startRow + 2);
+ header.createCell(0).setCellValue("鍦板尯 鍚嶇О");
+ header.createCell(1).setCellValue("鎸囨爣");
+ int col = 2;
+ for (int y : years) {
+ int monthCount = (y == currentYear) ? maxMonth : 12;
+ for (int m = 1; m <= monthCount; m++) {
+ header.createCell(col++).setCellValue(y + "骞�" + m + "鏈�");
+ header.createCell(col++).setCellValue(m + "鏈堜笌鍘诲勾鍚屾瘮");
+ }
+ header.createCell(col++).setCellValue(y + "骞寸疮璁�");
+ header.createCell(col++).setCellValue("绱涓庡幓骞村悓姣�");
+ }
+ sheet.createRow(startRow + 3);
+
+ String[] metrics = volume ? new String[]{
+ "鎬诲杩愰噺锛堜竾浜烘锛�",
+ "鍏朵腑锛氬叕璺彮绾垮杩愰噺锛堜竾浜烘锛�",
+ "鍩庨檯鍩庝埂鍏氦瀹㈣繍閲忥紙涓囦汉娆★級",
+ "鍩庨檯鍩庝埂宸℃父鍑虹瀹㈣繍閲忥紙涓囦汉娆★級",
+ "鍩庨檯鍩庝埂缃戠害杞﹀杩愰噺锛堜竾浜烘锛�"
+ } : new String[]{
+ "鎬绘梾瀹㈠懆杞噺锛堜竾浜哄叕閲岋級",
+ "鍏朵腑锛氬叕璺彮绾挎梾瀹㈠懆杞噺锛堜竾浜哄叕閲岋級",
+ "鍩庨檯鍩庝埂鍏氦鏃呭鍛ㄨ浆閲忥紙涓囦汉鍏噷锛�",
+ "鍩庨檯鍩庝埂宸℃父鍑虹鏃呭鍛ㄨ浆閲忥紙涓囦汉鍏噷锛�",
+ "鍩庨檯鍩庝埂缃戠害杞︽梾瀹㈠懆杞噺锛堜竾浜哄叕閲岋級"
+ };
+
+ int rowIdx = startRow + 4;
+ List<String> regions = new java.util.ArrayList<>();
+ regions.add("婀栧寳鐪�");
+ regions.addAll(RegionUtil.cityList());
+ for (String region : regions) {
+ String label = "婀栧寳鐪�".equals(region) ? "鍏ㄧ渷" : RegionUtil.shortName(region);
+ for (int i = 0; i < metrics.length; i++) {
+ Row row = sheet.createRow(rowIdx++);
+ row.createCell(0).setCellValue(label);
+ row.createCell(1).setCellValue(metrics[i]);
+ col = 2;
+ for (int y : years) {
+ int monthCount = (y == currentYear) ? maxMonth : 12;
+ for (int m = 1; m <= monthCount; m++) {
+ Double cur = midMetricValue(aggOf(data, y, m, region), i, volume);
+ setNumeric(row, col++, cur == null ? null : round(cur, 4));
+ Double base = midMetricValue(aggOf(data, y - 1, m, region), i, volume);
+ setNumeric(row, col++, yoy(cur, base));
+ }
+ Double cum = midCumOf(data, y, region, monthCount, i, volume);
+ setNumeric(row, col++, cum == null ? null : round(cum, 4));
+ Double cumBase = midCumOf(data, y - 1, region, monthCount, i, volume);
+ setNumeric(row, col++, yoy(cum, cumBase));
+ }
+ }
+ }
+ return rowIdx;
+ }
+
+ /** 涓彛寰勬寚鏍囧彇鍊硷細0=鎬婚噺 1=鍏矾鐝嚎 2-4=鍏氦/鍑虹/缃戠害杞︼紙鍩庡競瀹㈣繍妯″潡鏈帴鍏ワ紝鏆傜┖锛� */
+ private Double midMetricValue(PassengerAgg agg, int metric, boolean volume) {
+ if (agg == null) return null;
+ if (volume) {
+ switch (metric) {
+ case 0: return agg.passengerTotal / 10000.0;
+ case 1: return agg.passengerTotal / 10000.0;
+ default: return null;
+ }
+ }
+ switch (metric) {
+ case 0: return agg.turnoverTotal / 10000.0;
+ case 1: return agg.turnoverTotal / 10000.0;
+ default: return null;
+ }
+ }
+
+ private Double midCumOf(Map<Integer, Map<String, PassengerAgg>> data, int year, String region,
+ int monthCount, int metricIdx, boolean volume) {
+ double sum = 0.0;
+ boolean has = false;
+ for (int m = 1; m <= monthCount; m++) {
+ Double v = midMetricValue(aggOf(data, year, m, region), metricIdx, volume);
+ if (v != null) {
+ sum += v;
+ has = true;
+ }
+ }
+ return has ? sum : null;
+ }
+
+ /**
+ * 涓彛寰勬帓鍚嶏細宸﹀潡=褰撴湀锛堝杩愰噺/鍛ㄨ浆閲忓強鎺掑悕/鍚屾瘮/澧為�熸帓鍚嶏級锛屽彸鍧�=1-N鏈堢疮璁★紙鍚岀粨鏋勶級
+ */
+ /**
+ * 鐢熸垚_涓彛寰勬帓鍚�.xlsx锛氬崟鍧楃疮璁★紙閫� 1 涓湀=褰撴湀锛岄�� 1-6 鏈�=绱锛夛紝RANK/SUM 鍏紡淇濈暀銆�
+ */
+ public byte[] exportPassengerMidRank(String period, String mode) throws Exception {
+ int maxMonth = monthOf(period, mode);
+ int currentYear = Integer.parseInt(period.substring(0, 4));
+ File template = resolvePassengerTemplate("鐢熸垚_涓彛寰勬帓鍚�.xlsx");
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ Map<Integer, Map<String, double[][]>> mid = loadMidClassMap();
+ Row title = sheet.getRow(0);
+ if (title != null && title.getCell(0) != null) {
+ if (maxMonth == 12) {
+ title.getCell(0).setCellValue(currentYear + "骞�1-12鏈堝叏鐪佸垎甯傚窞绱瀹屾垚閬撹矾瀹㈣繍鐢熶骇鎯呭喌");
+ } else if (maxMonth == 1) {
+ title.getCell(0).setCellValue(currentYear + "骞�1鏈堝叏鐪佸垎甯傚窞瀹屾垚閬撹矾瀹㈣繍鐢熶骇鎯呭喌");
+ } else {
+ title.getCell(0).setCellValue(currentYear + "骞�1-" + maxMonth + "鏈堝叏鐪佸垎甯傚窞绱瀹屾垚閬撹矾瀹㈣繍鐢熶骇鎯呭喌");
+ }
+ }
+ // 鍙冲潡锛堝綋鏈堬級鏍囬 K1
+ if (title != null && title.getCell(10) != null) {
+ title.getCell(10).setCellValue(currentYear + "骞�" + maxMonth + "鏈堝叏鐪佸垎甯傚窞瀹屾垚閬撹矾瀹㈣繍鐢熶骇鎯呭喌");
+ }
+ // 鍏ㄧ渷琛� r3锛欱3/F3 涓� SUM 鍏紡淇濈暀锛汥3/H3 鍚屾瘮濉�硷紙0-based 鍒� 3/7锛�
+ setValOrBlank(sheet, 2, 3, yoyOf(midCumClass(mid, currentYear, "婀栧寳鐪�", maxMonth, 0, true),
+ midCumClass(mid, currentYear - 1, "婀栧寳鐪�", maxMonth, 0, true)));
+ setValOrBlank(sheet, 2, 7, yoyOf(midCumClass(mid, currentYear, "婀栧寳鐪�", maxMonth, 0, false),
+ midCumClass(mid, currentYear - 1, "婀栧寳鐪�", maxMonth, 0, false)));
+ // 鍙冲潡鍏ㄧ渷琛� N3/R3锛氬綋鏈堝悓姣旓紙L3/P3 涓� SUM 鍏紡淇濈暀锛�
+ setValOrBlank(sheet, 2, 13, yoyOf(midClassVal(mid, currentYear, maxMonth, "婀栧寳鐪�", 0, true),
+ midClassVal(mid, currentYear - 1, maxMonth, "婀栧寳鐪�", 0, true)));
+ setValOrBlank(sheet, 2, 17, yoyOf(midClassVal(mid, currentYear, maxMonth, "婀栧寳鐪�", 0, false),
+ midClassVal(mid, currentYear - 1, maxMonth, "婀栧寳鐪�", 0, false)));
+ // 甯傚窞琛� r4-20锛欱/F 绱鍊笺�丏/H 鍚屾瘮锛汣/E/G/I 鎺掑悕鍏紡淇濈暀
+ List<String> cities = RegionUtil.CITY_LIST;
+ for (int i = 0; i < cities.size(); i++) {
+ String city = cities.get(i);
+ int r0 = 3 + i;
+ double pass = midCumClass(mid, currentYear, city, maxMonth, 0, true);
+ double turn = midCumClass(mid, currentYear, city, maxMonth, 0, false);
+ double lastPass = midCumClass(mid, currentYear - 1, city, maxMonth, 0, true);
+ double lastTurn = midCumClass(mid, currentYear - 1, city, maxMonth, 0, false);
+ setValOrBlank(sheet, r0, 1, pass == 0 ? null : round(pass, 4));
+ setValOrBlank(sheet, r0, 3, yoyOf(pass, lastPass));
+ setValOrBlank(sheet, r0, 5, turn == 0 ? null : round(turn, 4));
+ setValOrBlank(sheet, r0, 7, yoyOf(turn, lastTurn));
+ // 鍙冲潡褰撴湀锛歀/P 鍊笺�丯/R 褰撴湀鍚屾瘮锛圡/O/Q/S 鎺掑悕鍏紡淇濈暀锛�
+ double mPass = midClassVal(mid, currentYear, maxMonth, city, 0, true);
+ double mTurn = midClassVal(mid, currentYear, maxMonth, city, 0, false);
+ double mLastPass = midClassVal(mid, currentYear - 1, maxMonth, city, 0, true);
+ double mLastTurn = midClassVal(mid, currentYear - 1, maxMonth, city, 0, false);
+ setValOrBlank(sheet, r0, 11, mPass == 0 ? null : round(mPass, 4));
+ setValOrBlank(sheet, r0, 13, mPass == 0 ? null : yoyOf(mPass, mLastPass));
+ setValOrBlank(sheet, r0, 15, mTurn == 0 ? null : round(mTurn, 4));
+ setValOrBlank(sheet, r0, 17, mTurn == 0 ? null : yoyOf(mTurn, mLastTurn));
+ }
+ recalc(wb);
+ return toBytes(wb);
+ }
+ }
+
+ /** 鍐欐暟鍊兼垨娓呯┖锛堝叕寮忓崟鍏冩牸淇濈暀涓嶅姩锛� */
+ private void setValOrBlank(Sheet sheet, int r0, int c0, Double v) {
+ Row row = sheet.getRow(r0);
+ if (row == null) return;
+ Cell c = row.getCell(c0);
+ if (c == null) return;
+ if (c.getCellType() == CellType.FORMULA) return;
+ if (v == null || v == 0.0) c.setBlank(); else c.setCellValue(v);
+ }
+
+ private Double yoyOf(double cur, double base) {
+ if (base == 0.0) return null;
+ return round((cur - base) / base, 4);
+ }
+
+ /** 涓彛寰勫垎绫荤疮璁★紙1..monthCount 鏈堟眰鍜岋級 */
+ private double midCumClass(Map<Integer, Map<String, double[][]>> mid, int year, String area, int monthCount, int k, boolean volume) {
+ double sum = 0.0;
+ boolean has = false;
+ for (int m = 1; m <= monthCount; m++) {
+ Map<String, double[][]> mm = mid.get(year * 100 + m);
+ if (mm == null) continue;
+ double[][] arr = mm.get(area);
+ if (arr == null) continue;
+ sum += volume ? arr[k][0] : arr[k][1];
+ has = true;
+ }
+ return has ? sum : 0.0;
+ }
+
+ /**
+ * 鐢熸垚_涓彛寰勫垎鏋�.xlsx锛氫互鏍蜂緥涓哄簳绋匡紝濉疮璁″杩愰噺/鍛ㄨ浆閲�/鍚屾瘮锛屽崰姣斿叕寮忎繚鐣欍��
+ */
+ public byte[] exportPassengerMidAnalysis(String period, String mode) throws Exception {
+ int maxMonth = monthOf(period, mode);
+ int currentYear = Integer.parseInt(period.substring(0, 4));
+ File template = resolvePassengerTemplate("鐢熸垚_涓彛寰勫垎鏋�.xlsx");
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ Map<Integer, Map<String, double[][]>> mid = loadMidClassMap();
+ Row title = sheet.getRow(0);
+ if (title != null && title.getCell(0) != null) {
+ title.getCell(0).setCellValue(currentYear + "骞�" + cumRange(maxMonth) + "涓彛寰勫杩愰噺鍙婂懆杞噺");
+ }
+ // r3=鎬� r4=鐝嚎 r5=鍏氦 r6=鍑虹 r7=缃戠害杞︼紙1-based锛夛紱鍒� B/C/F/G 濉�硷紝D/H 鍗犳瘮鍏紡淇濈暀
+ String[] names = {"鎬诲杩愰噺", "鍏矾鐝嚎", "鍩庨檯鍩庝埂鍏氦", "鍩庨檯鍩庝埂宸℃父鍑虹", "鍩庨檯鍩庝埂缃戠害杞�"};
+ int[] dims = {0, 1, 2, 3, 4};
+ for (int i = 0; i < names.length; i++) {
+ int r0 = 2 + i;
+ double pass = midCumClass(mid, currentYear, "婀栧寳鐪�", maxMonth, dims[i], true);
+ double turn = midCumClass(mid, currentYear, "婀栧寳鐪�", maxMonth, dims[i], false);
+ double lastPass = midCumClass(mid, currentYear - 1, "婀栧寳鐪�", maxMonth, dims[i], true);
+ double lastTurn = midCumClass(mid, currentYear - 1, "婀栧寳鐪�", maxMonth, dims[i], false);
+ setValOrBlank(sheet, r0, 1, pass == 0 ? null : round(pass, 4));
+ setValOrBlank(sheet, r0, 2, yoyOf(pass, lastPass));
+ setValOrBlank(sheet, r0, 5, turn == 0 ? null : round(turn, 4));
+ setValOrBlank(sheet, r0, 6, yoyOf(turn, lastTurn));
+ }
+ // 涓嬪崐鍧楋紙褰撴湀锛夛細鏍囬琛�9銆佹暟鎹11-15锛�0-based 8銆�10-14锛�
+ Row bottomTitle = sheet.getRow(8);
+ if (bottomTitle != null && bottomTitle.getCell(0) != null) {
+ bottomTitle.getCell(0).setCellValue(currentYear + "骞�" + maxMonth + "鏈堜腑鍙e緞瀹㈣繍閲忓強鍛ㄨ浆閲�");
+ }
+ for (int i = 0; i < names.length; i++) {
+ int r0 = 10 + i;
+ double pass = midClassVal(mid, currentYear, maxMonth, "婀栧寳鐪�", dims[i], true);
+ double turn = midClassVal(mid, currentYear, maxMonth, "婀栧寳鐪�", dims[i], false);
+ double lastPass = midClassVal(mid, currentYear - 1, maxMonth, "婀栧寳鐪�", dims[i], true);
+ double lastTurn = midClassVal(mid, currentYear - 1, maxMonth, "婀栧寳鐪�", dims[i], false);
+ setValOrBlank(sheet, r0, 1, pass == 0 ? null : round(pass, 4));
+ setValOrBlank(sheet, r0, 2, pass == 0 ? null : yoyOf(pass, lastPass));
+ setValOrBlank(sheet, r0, 5, turn == 0 ? null : round(turn, 4));
+ setValOrBlank(sheet, r0, 6, turn == 0 ? null : yoyOf(turn, lastTurn));
+ }
+ // 涓嬪崐鍧楀崰姣斿叕寮忕敱鏍蜂緥鎸囧悜涓婂崐鍧楋紙B$3/F$3锛夛紝鏀瑰啓涓烘湰鍧楁�昏锛圔$11/F$11锛夛紝琛�12-15
+ for (int i = 1; i < names.length; i++) {
+ int r0 = 10 + i;
+ Row rr = sheet.getRow(r0);
+ if (rr == null) continue;
+ Cell dc = rr.getCell(3);
+ if (dc != null && dc.getCellType() == CellType.FORMULA) {
+ dc.setCellFormula("B" + (r0 + 1) + "/B$11");
+ }
+ Cell hc = rr.getCell(7);
+ if (hc != null && hc.getCellType() == CellType.FORMULA) {
+ hc.setCellFormula("F" + (r0 + 1) + "/F$11");
+ }
+ }
+ recalc(wb);
+ return toBytes(wb);
+ }
+ }
+
+ private double nvlOf(Double v) {
+ return v == null ? Double.NaN : v;
+ }
+
+ private Double numOrNull(double v) {
+ return Double.isNaN(v) ? null : v;
+ }
+
+ /** 闄嶅簭鎺掑悕锛堟棤鏁版嵁 NaN 鎺掓渶鍚庯級锛岃繑鍥炲悇涓嬫爣瀵瑰簲鍚嶆 */
+ private int[] rankValues(double[] values) {
+ Integer[] order = new Integer[values.length];
+ for (int i = 0; i < values.length; i++) order[i] = i;
+ java.util.Arrays.sort(order, (a, b) -> {
+ boolean na = Double.isNaN(values[a]);
+ boolean nb = Double.isNaN(values[b]);
+ if (na && nb) return 0;
+ if (na) return 1;
+ if (nb) return -1;
+ return Double.compare(values[b], values[a]);
+ });
+ int[] ranks = new int[values.length];
+ for (int i = 0; i < order.length; i++) ranks[order[i]] = i + 1;
+ return ranks;
+ }
+
+ // ==================== 5. 鐢熸垚_鑳借繍姹囨�昏〃锛圚204 閬撹矾璐ц繍杞﹁締鑳芥簮娑堣�楁儏鍐碉級 ====================
+
+ /** 鐕冩枡绫诲瀷鐮� -> 鍛ㄨ浆閲忓崟鑰楁姌绠楃郴鏁帮紙鍗冨厠鏍囧噯鐓ゆ姌绠楋級 */
+ private static final Map<String, Double> ENERGY_FUEL_COEFF = new HashMap<>();
+
+ static {
+ ENERGY_FUEL_COEFF.put("01", 0.73 * 1.4714); // 姹芥补
+ ENERGY_FUEL_COEFF.put("02", 0.86 * 1.4571); // 鏌存补
+ ENERGY_FUEL_COEFF.put("03", 1.7572); // 鍘嬬缉澶╃劧姘�
+ ENERGY_FUEL_COEFF.put("04", 1.7572); // 娑插寲澶╃劧姘�
+ ENERGY_FUEL_COEFF.put("07", 0.1229); // 鐢靛姩
+ ENERGY_FUEL_COEFF.put("08", 0.3329 * 12.1951); // 鐕冩枡鐢垫睜锛堟阿姘旓級
+ }
+
+ /** 鐕冩枡鐮� -> 姹囨�昏〃琛屽悕锛堜笌妯℃澘琛岄『搴忎竴鑷达級 */
+ private static final String[][] ENERGY_FUEL_ROWS = {
+ {"鏌存补杞�", "02"},
+ {"姹芥补杞�", "01"},
+ {"娑插寲澶╃劧姘旇溅", "04"},
+ {"鍘嬬缉澶╃劧姘旇溅", "03"},
+ {"绾數鍔ㄨ溅", "07"},
+ {"鐕冩枡鐢垫睜杞�", "08"}
+ };
+
+ /**
+ * 鑳借繍姹囨�昏〃锛氭寜鐕冩枡绫诲瀷鍒嗙粍姹囨�伙紝鍏ㄧ渷 + 鍚勫競宸炲悇涓�寮� sheet
+ */
+ public byte[] exportEnergySummary(String period) throws Exception {
+ List<EnergyVehicleQuarterly> list = energyMapper.selectList(
+ new LambdaQueryWrapper<EnergyVehicleQuarterly>()
+ .eq(EnergyVehicleQuarterly::getReportPeriod, period));
+ int quarter = (parseMonth(period) + 2) / 3;
+ String[] QUARTER_CN = {"涓�", "浜�", "涓�", "鍥�"};
+ String title = period.substring(0, 4) + "骞寸" + QUARTER_CN[quarter - 1] + "瀛e害鑳借�楁眹鎬绘儏鍐佃〃";
+
+ Map<String, FuelAgg> province = new HashMap<>();
+ Map<String, Map<String, FuelAgg>> cityMap = new HashMap<>();
+ for (EnergyVehicleQuarterly e : list) {
+ String code = e.getFuelTypeCode();
+ if (code == null || code.trim().isEmpty()) continue;
+ province.computeIfAbsent(code.trim(), k -> new FuelAgg()).add(e);
+ String city = RegionUtil.cityByCode(e.getRegionCode());
+ if (city != null) {
+ cityMap.computeIfAbsent(city, k -> new HashMap<>())
+ .computeIfAbsent(code.trim(), k2 -> new FuelAgg()).add(e);
+ }
+ }
+
+ // 浠� 妯℃澘_鑳借繍姹囨�昏〃 .xlsx 涓哄簳绋匡細淇濈暀鏍囬/琛ㄥご/鍚堝苟/鍏紡/鍒楀/鏍峰紡锛屼粎鏇挎崲鏁版嵁鍖烘暟鍊�
+ File template = resolveAnyTemplate(energyTemplateDir, "鐢熸垚_鑳借繍姹囨�昏〃.xlsx");
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet base = wb.getSheetAt(0);
+ base.getRow(0).getCell(0).setCellValue(title);
+ fillEnergyTemplateSheet(base, province);
+ for (String city : RegionUtil.cityList()) {
+ Map<String, FuelAgg> agg = cityMap.get(city);
+ if (agg == null || agg.isEmpty()) continue;
+ Sheet s = wb.cloneSheet(0);
+ wb.setSheetName(wb.getSheetIndex(s), RegionUtil.shortName(city) + "鑳借�楁眹鎬�");
+ s.getRow(0).getCell(0).setCellValue(title);
+ fillEnergyTemplateSheet(s, agg);
+ }
+ recalc(wb);
+ clearFormulaErrorsAll(wb); // 鏃犲幓骞存暟鎹殑鍚屾瘮/澧為�熷叕寮� #DIV/0! 鈫� 娓呯┖
+ return toBytes(wb);
+ }
+ }
+
+ /** 鑳借�楁眹鎬绘ā鏉垮~鍏咃細1-based 绗�3~8琛屼负 鏌存补/姹芥补/娑插寲澶╃劧/鍘嬬缉澶╃劧/绾數/鐕冩枡鐢垫睜锛汥/J/L/M 涓哄叕寮忓垪锛屼粎濉暟鍊煎垪 */
+ private void fillEnergyTemplateSheet(Sheet sheet, Map<String, FuelAgg> data) {
+ for (int i = 0; i < ENERGY_FUEL_ROWS.length; i++) {
+ Row row = sheet.getRow(2 + i);
+ if (row == null) row = sheet.createRow(2 + i);
+ FuelAgg agg = data.get(ENERGY_FUEL_ROWS[i][1]);
+ if (agg == null || agg.count == 0) {
+ setEnergyValue(row, 1, null);
+ setEnergyValue(row, 2, null);
+ setEnergyValue(row, 4, null);
+ setEnergyValue(row, 5, null);
+ setEnergyValue(row, 6, null);
+ setEnergyValue(row, 7, null);
+ setEnergyValue(row, 8, null);
+ setEnergyValue(row, 10, null);
+ continue;
+ }
+ setEnergyValue(row, 1, (double) agg.count);
+ setEnergyValue(row, 2, agg.totalTonnage);
+ setEnergyValue(row, 4, agg.totalMileage);
+ setEnergyValue(row, 5, agg.loadedMileage);
+ setEnergyValue(row, 6, agg.emptyMileage);
+ setEnergyValue(row, 7, agg.freight);
+ setEnergyValue(row, 8, agg.turnover);
+ setEnergyValue(row, 10, agg.fuelConsumption);
+ }
+ }
+
+ /** 鍐欒兘鑰楁暟鍊煎垪锛氭湁鍊煎啓鍏ワ紝鏃犲�兼竻绌烘ā鏉挎牱渚嬶紱鍏紡鍒楋紙D/J/L/M锛変笉鍔� */
+ private void setEnergyValue(Row row, int colIdx, Double v) {
+ Cell c = row.getCell(colIdx);
+ if (c != null && c.getCellType() == org.apache.poi.ss.usermodel.CellType.FORMULA) return;
+ if (c == null) c = row.createCell(colIdx);
+ if (v == null) c.setBlank(); else c.setCellValue(v);
+ }
+
+ /** 鑳借�楁眹鎬伙細鎸夌噧鏂欑被鍨嬭仛鍚� */
+ private static class FuelAgg {
+ int count;
+ double totalTonnage;
+ double totalMileage;
+ double loadedMileage;
+ double emptyMileage;
+ double freight;
+ double turnover;
+ double fuelConsumption;
+
+ void add(EnergyVehicleQuarterly e) {
+ count++;
+ totalTonnage += nz(e.getMarkedTonnage());
+ totalMileage += nz(e.getTotalMileage());
+ loadedMileage += nz(e.getLoadedMileage());
+ emptyMileage += nz(e.getEmptyMileage());
+ freight += nz(e.getFreight());
+ turnover += nz(e.getTurnover());
+ fuelConsumption += nz(e.getFuelConsumption());
+ }
+
+ private double nz(Double v) {
+ return v == null ? 0.0 : v;
+ }
+ }
+
// ==================== 閫氱敤杈呭姪 ====================
private int parseMonth(String period) {
return Integer.parseInt(period.split("-")[1]);
+ }
+
+ private int monthOf(String period, String mode) {
+ return "year".equalsIgnoreCase(mode) ? 12 : parseMonth(period);
+ }
+
+ /** 绱鍖洪棿鏂囨锛�1 鏈堟樉绀� "1鏈�"锛屽叾浣欐樉绀� "1-N鏈�"锛堥伩鍏嶅嚭鐜� "1-1鏈�"锛� */
+ private String cumRange(int month) {
+ return month <= 1 ? "1鏈�" : "1-" + month + "鏈�";
+ }
+
+ /** 鏃呭鍒嗗競宸�/涓彛寰勬槑缁嗘ā鏉胯〃澶村勾浠藉姩鎬佸寲锛氭妸 "2026骞�1鏈�"鈥�"2026骞�6鏈�"銆�"2026骞寸疮璁�" 鐨勫勾浠芥崲鎴愭墍閫夊勾 */
+ private void fixPassengerHeaderYear(Sheet sheet, int year) {
+ java.util.regex.Pattern p = java.util.regex.Pattern.compile("^\\d{4}骞�");
+ for (int r = 1; r <= 3; r++) {
+ Row row = sheet.getRow(r);
+ if (row == null) continue;
+ for (Cell cell : row) {
+ if (cell.getCellType() != CellType.STRING) continue;
+ String v = cell.getStringCellValue();
+ if (v == null || v.isEmpty()) continue;
+ String nv = p.matcher(v).replaceFirst(year + "骞�");
+ if (!nv.equals(v)) cell.setCellValue(nv);
+ }
+ }
}
private String pad(int m) {
@@ -808,11 +2741,2098 @@
sheet.setColumnWidth(1, 22 * 256);
}
- private byte[] toBytes(XSSFWorkbook wb) throws Exception {
+
+ // ==================== 鍩庡競瀹㈣繍锛堝叕浜わ級鍒嗗競宸炴槑缁� ====================
+
+ /** 鐢熸垚_鍩庡競鍏氦瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx锛堜互 鍩庡競鍏氦_妯℃澘.xlsx 涓哄簳绋匡紝淇濈暀妯℃澘鏍煎紡涓庡叕寮忥級 */
+ public byte[] exportCityBusDetail(String period, String mode) throws Exception {
+ int year = Integer.parseInt(period.split("-")[0]);
+ int month = monthOf(period, mode);
+ return exportCityByTemplate("鐢熸垚_鍩庡競鍏氦瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx", period, mode,
+ loadCityBusByMonth(year + "-", month),
+ loadCityBusByMonth((year - 1) + "-", month));
+ }
+ /** 鍔犺浇鏌愬勾 1..limit 鏈堝煄甯傚叕浜や紒涓氭暟鎹紝鎸� 鏈� 鈫� 甯傚窞 鈫� [瀹㈣繍閲�,鍛ㄨ浆閲�,鍩庡競鍐呭杩愰噺,鍩庡競鍐呭懆杞噺] 姹囨�伙紱"鍏ㄧ渷" 涓哄叏閮ㄥ競宸炲悎璁� */
+ private Map<Integer, Map<String, double[]>> loadCityBusByMonth(String yearPrefix, int limit) {
+ Map<Integer, Map<String, double[]>> monthCity = new java.util.LinkedHashMap<>();
+ List<CityBusMonthly> rows = cityBusMapper.selectList(
+ new LambdaQueryWrapper<CityBusMonthly>()
+ .likeRight(CityBusMonthly::getReportPeriod, yearPrefix));
+ for (CityBusMonthly r : rows) {
+ int m = monthOf(r.getReportPeriod());
+ if (m < 1 || m > limit) continue;
+ String city = r.getCity() == null ? "鏈煡" : r.getCity();
+ Map<String, double[]> cityMap = monthCity.computeIfAbsent(m, k -> new HashMap<>());
+ double[] arr = cityMap.computeIfAbsent(city, k -> new double[4]);
+ arr[0] += nz(r.getPassengerVolume());
+ arr[1] += nz(r.getTurnover());
+ arr[2] += nz(r.getPassengerCity());
+ arr[3] += nz(r.getTurnoverCity());
+ double[] prov = cityMap.computeIfAbsent("鍏ㄧ渷", k -> new double[4]);
+ prov[0] += nz(r.getPassengerVolume());
+ prov[1] += nz(r.getTurnover());
+ prov[2] += nz(r.getPassengerCity());
+ prov[3] += nz(r.getTurnoverCity());
+ }
+ return monthCity;
+ }
+
+ private int monthOf(String reportPeriod) {
+ if (reportPeriod == null) return 0;
+ String[] parts = reportPeriod.split("-");
+ if (parts.length < 2) return 0;
+ try {
+ return Integer.parseInt(parts[1]);
+ } catch (Exception e) {
+ return 0;
+ }
+ }
+
+ private double cityBusVal(Map<Integer, Map<String, double[]>> monthCity, String area, int m, int idx) {
+ Map<String, double[]> cityMap = monthCity.get(m);
+ if (cityMap == null) return 0;
+ double[] arr = cityMap.get(area);
+ if (arr == null) return 0;
+ return idx < arr.length ? arr[idx] : 0;
+ }
+
+ // ==================== 鍩庡競瀹㈣繍锛堝贰娓稿嚭绉燂級鍒嗗競宸炴槑缁� ====================
+
+ /** 鐢熸垚_宸℃父鍑虹瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx锛堜互 宸℃父鍑虹_妯℃澘.xlsx 涓哄簳绋匡紝淇濈暀妯℃澘鏍煎紡涓庡叕寮忥級 */
+ public byte[] exportCityTaxiDetail(String period, String mode) throws Exception {
+ int year = Integer.parseInt(period.split("-")[0]);
+ int month = monthOf(period, mode);
+ return exportCityByTemplate("鐢熸垚_宸℃父鍑虹瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx", period, mode,
+ loadCityTaxiByMonth(year + "-", month),
+ loadCityTaxiByMonth((year - 1) + "-", month));
+ }
+ /** 鍔犺浇鏌愬勾 1..limit 鏈堝贰娓稿嚭绉熸暟鎹紝鎸� 鏈� 鈫� 甯傚窞 鈫� [瀹㈣繍閲�,鍛ㄨ浆閲�,鍩庡競鍐呭杩愰噺,鍩庡競鍐呭懆杞噺] 姹囨�伙紱"鍏ㄧ渷" 涓哄叏閮ㄥ競宸炲悎璁� */
+ private Map<Integer, Map<String, double[]>> loadCityTaxiByMonth(String yearPrefix, int limit) {
+ Map<Integer, Map<String, double[]>> monthCity = new java.util.LinkedHashMap<>();
+ List<CityTaxiMonthly> rows = cityTaxiMapper.selectList(
+ new LambdaQueryWrapper<CityTaxiMonthly>()
+ .likeRight(CityTaxiMonthly::getReportPeriod, yearPrefix));
+ for (CityTaxiMonthly r : rows) {
+ int m = monthOf(r.getReportPeriod());
+ if (m < 1 || m > limit) continue;
+ String city = r.getCity() == null ? "鏈煡" : r.getCity();
+ Map<String, double[]> cityMap = monthCity.computeIfAbsent(m, k -> new HashMap<>());
+ double[] arr = cityMap.computeIfAbsent(city, k -> new double[4]);
+ arr[0] += nz(r.getPassengerVolume());
+ arr[1] += nz(r.getTurnover());
+ arr[2] += nz(r.getPassengerCity());
+ arr[3] += nz(r.getTurnoverCity());
+ double[] prov = cityMap.computeIfAbsent("鍏ㄧ渷", k -> new double[4]);
+ prov[0] += nz(r.getPassengerVolume());
+ prov[1] += nz(r.getTurnover());
+ prov[2] += nz(r.getPassengerCity());
+ prov[3] += nz(r.getTurnoverCity());
+ }
+ return monthCity;
+ }
+
+ private double cityTaxiVal(Map<Integer, Map<String, double[]>> monthCity, String area, int m, int idx) {
+ Map<String, double[]> cityMap = monthCity.get(m);
+ if (cityMap == null) return 0;
+ double[] arr = cityMap.get(area);
+ if (arr == null) return 0;
+ return idx < arr.length ? arr[idx] : 0;
+ }
+
+ // ==================== 鍩庡競瀹㈣繍锛堣建閬�/杞浮锛夊垎甯傚窞鏄庣粏 ====================
+
+ /** 鐢熸垚_杞ㄩ亾杞浮瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx锛堜互 杞ㄩ亾銆佽疆娓妯℃澘.xlsx 涓哄簳绋匡紝杞ㄩ亾=鍏ㄧ渷/姝︽眽/榛勭煶锛岃疆娓�=鍏ㄧ渷/姝︽眽锛� */
+ public byte[] exportCityRailFerryDetail(String period, String mode) throws Exception {
+ int year = Integer.parseInt(period.split("-")[0]);
+ int month = monthOf(period, mode);
+ Map<Integer, Map<String, double[]>> monthCity = loadCityRailFerryByMonth(year + "-", month);
+ File template = resolveTemplate("鐢熸垚_杞ㄩ亾杞浮瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx");
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ dynamicTitle(sheet, year, month); // 鏍囬鎸夋姤琛ㄦ湡鍔ㄦ�佸寲锛堜笉鍐欐骞翠唤/鏈堜唤锛�
+ // 杞ㄩ亾锛氬杩愰噺琛� 4(鍏ㄧ渷)/6(姝︽眽)/8(榛勭煶)锛屽懆杞噺琛屼负 +1锛涙寚鏍� 0=杞ㄩ亾瀹㈣繍閲� 1=杞ㄩ亾鍛ㄨ浆閲�
+ fillRailFerryBlock(sheet, monthCity, month, new String[][]{{"鍏ㄧ渷", "3"}, {"姝︽眽甯�", "5"}, {"榛勭煶甯�", "7"}}, 0);
+ // 杞浮锛氬杩愰噺琛� 13(鍏ㄧ渷)/15(姝︽眽)锛涙寚鏍� 2=杞浮瀹㈣繍閲� 3=杞浮鍛ㄨ浆閲�
+ fillRailFerryBlock(sheet, monthCity, month, new String[][]{{"鍏ㄧ渷", "12"}, {"姝︽眽甯�", "14"}}, 2);
+ recalc(wb);
+ clearFormulaErrorCells(sheet, 3, sheet.getLastRowNum(), 1, 39);
+ fixCityMonthHeaderText(sheet);
+ return toBytes(wb);
+ }
+ }
+
+ /** 鍔犺浇鏌愬勾 1..limit 鏈堣建閬�/杞浮鏁版嵁锛氭湀 鈫� 甯傚窞 鈫� [杞ㄩ亾瀹㈣繍閲�,杞ㄩ亾鍛ㄨ浆閲�,杞浮瀹㈣繍閲�,杞浮鍛ㄨ浆閲廬锛屽惈"鍏ㄧ渷" */
+ private Map<Integer, Map<String, double[]>> loadCityRailFerryByMonth(String yearPrefix, int limit) {
+ Map<Integer, Map<String, double[]>> monthCity = new java.util.LinkedHashMap<>();
+ List<CityBusMonthly> rows = cityBusMapper.selectList(
+ new LambdaQueryWrapper<CityBusMonthly>().likeRight(CityBusMonthly::getReportPeriod, yearPrefix));
+ for (CityBusMonthly r : rows) {
+ int m = monthOf(r.getReportPeriod());
+ if (m < 1 || m > limit) continue;
+ String city = r.getCity() == null ? "鏈煡" : r.getCity();
+ Map<String, double[]> cityMap = monthCity.computeIfAbsent(m, k -> new HashMap<>());
+ double[] arr = cityMap.computeIfAbsent(city, k -> new double[4]);
+ arr[0] += nz(r.getRailPassengerVolume());
+ arr[1] += nz(r.getRailTurnover());
+ arr[2] += nz(r.getFerryPassengerVolume());
+ arr[3] += nz(r.getFerryTurnover());
+ double[] prov = cityMap.computeIfAbsent("鍏ㄧ渷", k -> new double[4]);
+ prov[0] += nz(r.getRailPassengerVolume());
+ prov[1] += nz(r.getRailTurnover());
+ prov[2] += nz(r.getFerryPassengerVolume());
+ prov[3] += nz(r.getFerryTurnover());
+ }
+ return monthCity;
+ }
+
+ /** 濉厖杞ㄩ亾/杞浮鍧楋細baseIdx 涓哄杩愰噺鎸囨爣锛屽懆杞噺鎸囨爣 = baseIdx+1锛�2026 鏈堝害鍒� C..O锛�2025 鍒� T.. 鏃犳暟鎹垯娓呯┖ */
+ private void fillRailFerryBlock(Sheet sheet, Map<Integer, Map<String, double[]>> monthCity, int month,
+ String[][] areaRows, int baseIdx) {
+ for (String[] ar : areaRows) {
+ String area = ar[0];
+ int paxRow = Integer.parseInt(ar[1]);
+ for (int m = 1; m <= month; m++) {
+ setDataCell(sheet, paxRow, 2 + (m - 1) * 2, railFerryVal(monthCity, area, m, baseIdx));
+ setDataCell(sheet, paxRow + 1, 2 + (m - 1) * 2, railFerryVal(monthCity, area, m, baseIdx + 1));
+ }
+ for (int m = 1; m <= 12; m++) {
+ setDataCell(sheet, paxRow, 19 + (m - 1) * 2, 0);
+ setDataCell(sheet, paxRow + 1, 19 + (m - 1) * 2, 0);
+ }
+ }
+ }
+
+ private double railFerryVal(Map<Integer, Map<String, double[]>> monthCity, String area, int m, int idx) {
+ Map<String, double[]> cityMap = monthCity.get(m);
+ if (cityMap == null) return 0;
+ double[] arr = cityMap.get(area);
+ if (arr == null) return 0;
+ return idx < arr.length ? arr[idx] : 0;
+ }
+
+ /** 鍐欐暟鎹崟鍏冩牸锛氬師涓哄叕寮忓垯淇濈暀锛堝叏鐪佹眰鍜�/鎺掑悕鍏紡锛夛紱鍚﹀垯鏈夊�煎啓鍏ャ�佹棤鍊兼竻绌烘ā鏉挎牱渚� */
+ private void setDataCell(Sheet sheet, int rowIdx, int colIdx, double v) {
+ Row row = sheet.getRow(rowIdx);
+ if (row == null) row = sheet.createRow(rowIdx);
+ Cell c = row.getCell(colIdx);
+ if (c != null && c.getCellType() == org.apache.poi.ss.usermodel.CellType.FORMULA) return;
+ if (c == null) c = row.createCell(colIdx);
+ if (v == 0) c.setBlank(); else c.setCellValue(round(v, 2));
+ }
+
+ /** 鏄惧紡鍐欏叆 0锛坰etDataCell 瀵� 0 缃┖锛涙眹鎬昏〃缃戠害杞﹁闇�瑕佹樉绀� 0锛� */
+ private void setZeroCell(Sheet sheet, int rowIdx, int colIdx) {
+ Row row = sheet.getRow(rowIdx);
+ if (row == null) row = sheet.createRow(rowIdx);
+ Cell c = row.getCell(colIdx);
+ if (c != null && c.getCellType() == org.apache.poi.ss.usermodel.CellType.FORMULA) return;
+ if (c == null) c = row.createCell(colIdx);
+ c.setCellValue(0.0);
+ }
+ /** 閲嶇畻鍏紡缂撳瓨鍊硷紙淇濈暀鍏紡锛屾眰鍊煎紓甯稿拷鐣ワ級 */
+ private void recalc(XSSFWorkbook wb) {
+ try {
+ wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
+ } catch (Exception e) {
+ log.warn("鍩庡競瀹㈣繍妯℃澘鍏紡姹傚�煎け璐�: {}", e.getMessage());
+ }
+ }
+
+ // ==================== 鍩庡競瀹㈣繍 鍒嗗競宸炵疮璁★紙鍩庡競鍒嗗競宸瀇妯℃澘 / 鍩庡競瀹㈣繍鍚勫競宸炴槑缁嗚〃_妯℃澘锛� ====================
+
+ /** 鐢熸垚_鍩庡競瀹㈣繍瀹㈣繍閲忓垎甯傚窞绱.xlsx锛堜互 鍩庡競鍒嗗競宸瀇妯℃澘.xlsx / 鍩庡競瀹㈣繍鍚勫競宸炴槑缁嗚〃_妯℃澘.xlsx 涓哄簳绋匡紱缃戠害杞﹀垪鏃犳簮鏁版嵁鐣欑┖锛� */
+ public byte[] exportCityPassengerCitySum(String templateFileName, String period, String mode) throws Exception {
+ int year = Integer.parseInt(period.split("-")[0]);
+ int month = monthOf(period, mode);
+ Map<String, double[]> cum = loadCityPassengerCumulative(year + "-", month);
+ Map<String, double[]> monthMap = loadCityPassengerMonthMap(year + "-", month);
+ File template = resolveTemplate(templateFileName);
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ dynamicTitle(sheet, year, month); // 鏍囬鎸夋姤琛ㄦ湡鍔ㄦ�佸寲
+ List<String> areas = new java.util.ArrayList<>();
+ areas.add("鍏ㄧ渷");
+ areas.addAll(RegionUtil.cityList());
+ fillCitySumBlock(sheet, cum, areas, 4, 0); // 绱瀹㈣繍閲忓尯锛堝崟浣嶏細涓囦汉娆★紝POI 0 鍩猴紝琛�5-22锛�
+ fillCitySumBlock(sheet, cum, areas, 26, 1); // 绱鍛ㄨ浆閲忓尯锛堝崟浣嶏細涓囦汉娆″叕閲岋紝POI 0 鍩猴紝琛�27-44锛�
+ // 褰撴湀鍧楁爣棰橈紙0鍩鸿44/66锛変笌鏁版嵁锛�0鍩鸿48-65/70-87锛�
+ Row pTitle = sheet.getRow(44);
+ if (pTitle != null && pTitle.getCell(0) != null) {
+ pTitle.getCell(0).setCellValue("鍩庡競瀹㈣繍瀹㈣繍閲忓垎甯傚窞" + month + "鏈堟儏鍐�");
+ }
+ Row tTitle = sheet.getRow(66);
+ if (tTitle != null && tTitle.getCell(0) != null) {
+ tTitle.getCell(0).setCellValue("鍩庡競瀹㈣繍瀹㈣繍鍛ㄨ浆閲忓垎甯傚窞" + month + "鏈堟儏鍐�");
+ }
+ fillCitySumBlock(sheet, monthMap, areas, 48, 0); // 褰撴湀瀹㈣繍閲忓尯锛堣49-66锛�
+ fillCitySumBlock(sheet, monthMap, areas, 70, 1); // 褰撴湀鍛ㄨ浆閲忓尯锛堣71-88锛�
+ // 褰撴湀鍧楁帓鍚�/鍗犳瘮鍏紡鐢辩疮璁″潡澶嶅埗鑰屾潵锛孯ANK 鑼冨洿涓庡崰姣斿垎姣嶉渶鏀规寚褰撴湀鍧楄嚜韬
+ repairCityMonthRankShare(sheet, 50, 66, 49);
+ repairCityMonthRankShare(sheet, 72, 88, 71);
+ recalc(wb);
+ clearFormulaErrorsAll(wb); // 鏃犲幓骞寸疮璁$殑鍗犳瘮/澧為�熷叕寮� #DIV/0! 鈫� 娓呯┖
+ return toBytes(wb);
+ }
+ }
+
+ /** 濉厖涓�涓疮璁″尯锛歴tartRow 璧锋瘡鍦板尯 1 琛岋紱paxTurnIdx=0 鐢ㄥ杩愰噺銆�1 鐢ㄥ懆杞噺 */
+ private void fillCitySumBlock(Sheet sheet, Map<String, double[]> cum, List<String> areas, int startRow, int paxTurnIdx) {
+ int rowIdx = startRow;
+ for (String area : areas) {
+ double[] v = cum.get(area);
+ double bus = v == null ? 0 : v[paxTurnIdx == 0 ? 0 : 1];
+ double taxi = v == null ? 0 : v[paxTurnIdx == 0 ? 2 : 3];
+ double rail = v == null ? 0 : v[paxTurnIdx == 0 ? 4 : 5];
+ double ferry = v == null ? 0 : v[paxTurnIdx == 0 ? 6 : 7];
+ double total = bus + taxi + rail + ferry; // 缃戠害杞︽棤婧愭暟鎹紝涓嶈
+ setDataCell(sheet, rowIdx, 1, total); // B 鎬荤疮璁�
+ setDataCell(sheet, rowIdx, 6, bus); // G 鍏氦
+ setDataCell(sheet, rowIdx, 11, taxi); // L 鍑虹
+ setDataCell(sheet, rowIdx, 16, 0); // Q 缃戠害杞︼紙鏃犳簮鏁版嵁鈫掓竻绌烘牱渚嬶級
+ setDataCell(sheet, rowIdx, 21, rail); // V 杞ㄩ亾
+ setDataCell(sheet, rowIdx, 23, ferry); // X 杞浮
+ // 澧為�熷垪 E/J/O/T/W/Y锛氭棤鍘诲勾鍚屾湡绱 鈫� 娓呯┖妯℃澘鏍蜂緥锛堟帓鍚�/鍗犳瘮鍏紡淇濈暀锛�
+ setDataCell(sheet, rowIdx, 4, 0);
+ setDataCell(sheet, rowIdx, 9, 0);
+ setDataCell(sheet, rowIdx, 14, 0);
+ setDataCell(sheet, rowIdx, 19, 0);
+ setDataCell(sheet, rowIdx, 22, 0);
+ setDataCell(sheet, rowIdx, 24, 0);
+ rowIdx++;
+ }
+ }
+
+ /** 褰撴湀鍧楁帓鍚�/鍗犳瘮鍏紡淇锛氭ā鏉垮綋鏈堝潡鐢辩疮璁″潡澶嶅埗鑰屾潵锛孯ANK 鑼冨洿涓庡崰姣斿垎姣嶉渶鏀规寚褰撴湀鍧楄嚜韬 */
+ private void repairCityMonthRankShare(Sheet sheet, int firstDataRow1, int lastDataRow1, int provRow1) {
+ String[] groups = {"B", "G", "L", "Q"};
+ String[] growth = {"E", "J", "O", "T"};
+ for (int r = firstDataRow1; r <= lastDataRow1; r++) {
+ int r0 = r - 1;
+ for (int g = 0; g < 4; g++) {
+ String base = groups[g];
+ String grow = growth[g];
+ setFormulaIfFormula(sheet, r0, 2 + g * 5,
+ "RANK(" + base + r + "," + base + "$" + firstDataRow1 + ":" + base + "$" + lastDataRow1 + ")");
+ setFormulaIfFormula(sheet, r0, 3 + g * 5, base + r + "/" + base + "$" + provRow1);
+ setFormulaIfFormula(sheet, r0, 5 + g * 5,
+ "RANK(" + grow + r + "," + grow + "$" + firstDataRow1 + ":" + grow + "$" + lastDataRow1 + ")");
+ }
+ }
+ }
+
+ /** 鍗曞厓鏍煎師涓哄叕寮忔椂鏀瑰啓鍏紡锛堟帓鍚�/鍗犳瘮鍒楋級锛岄潪鍏紡鍗曞厓鏍间笉鍔紙淇濇寔妯℃澘寮忔牱锛� */
+ private void setFormulaIfFormula(Sheet sheet, int rowIdx, int colIdx, String formula) {
+ Row row = sheet.getRow(rowIdx);
+ if (row == null) return;
+ Cell c = row.getCell(colIdx);
+ if (c == null || c.getCellType() != CellType.FORMULA) return;
+ c.setCellFormula(formula);
+ }
+
+ /** 鏌愬勾 1..limit 鏈堝煄甯傚杩愮疮璁★細city 鈫� [鍏氦瀹㈣繍閲�,鍏氦鍛ㄨ浆閲�,鍑虹瀹㈣繍閲�,鍑虹鍛ㄨ浆閲�,杞ㄩ亾瀹㈣繍閲�,杞ㄩ亾鍛ㄨ浆閲�,杞浮瀹㈣繍閲�,杞浮鍛ㄨ浆閲廬锛屽惈"鍏ㄧ渷" */
+ private Map<String, double[]> loadCityPassengerCumulative(String yearPrefix, int limit) {
+ Map<String, double[]> cum = new HashMap<>();
+ for (CityBusMonthly r : cityBusMapper.selectList(
+ new LambdaQueryWrapper<CityBusMonthly>().likeRight(CityBusMonthly::getReportPeriod, yearPrefix))) {
+ int m = monthOf(r.getReportPeriod());
+ if (m < 1 || m > limit) continue;
+ String city = r.getCity() == null ? "鏈煡" : r.getCity();
+ double[] a = cum.computeIfAbsent(city, k -> new double[8]);
+ a[0] += nz(r.getPassengerVolume());
+ a[1] += nz(r.getTurnover());
+ a[4] += nz(r.getRailPassengerVolume());
+ a[5] += nz(r.getRailTurnover());
+ a[6] += nz(r.getFerryPassengerVolume());
+ a[7] += nz(r.getFerryTurnover());
+ double[] p = cum.computeIfAbsent("鍏ㄧ渷", k -> new double[8]);
+ p[0] += nz(r.getPassengerVolume());
+ p[1] += nz(r.getTurnover());
+ p[4] += nz(r.getRailPassengerVolume());
+ p[5] += nz(r.getRailTurnover());
+ p[6] += nz(r.getFerryPassengerVolume());
+ p[7] += nz(r.getFerryTurnover());
+ }
+ for (CityTaxiMonthly r : cityTaxiMapper.selectList(
+ new LambdaQueryWrapper<CityTaxiMonthly>().likeRight(CityTaxiMonthly::getReportPeriod, yearPrefix))) {
+ int m = monthOf(r.getReportPeriod());
+ if (m < 1 || m > limit) continue;
+ String city = r.getCity() == null ? "鏈煡" : r.getCity();
+ double[] a = cum.computeIfAbsent(city, k -> new double[8]);
+ a[2] += nz(r.getPassengerVolume());
+ a[3] += nz(r.getTurnover());
+ double[] p = cum.computeIfAbsent("鍏ㄧ渷", k -> new double[8]);
+ p[2] += nz(r.getPassengerVolume());
+ p[3] += nz(r.getTurnover());
+ }
+ return cum;
+ }
+
+ /** 鏌愬勾鍗曟湀鍩庡競瀹㈣繍鏁版嵁锛歝ity 鈫� 8 缁存暟缁勶紙鍙e緞鍚岀疮璁★級锛屽惈"鍏ㄧ渷"锛�= month 绱 - (month-1) 绱 */
+ private Map<String, double[]> loadCityPassengerMonthMap(String yearPrefix, int month) {
+ Map<String, double[]> cum = loadCityPassengerCumulative(yearPrefix, month);
+ if (month <= 1) return cum;
+ Map<String, double[]> pre = loadCityPassengerCumulative(yearPrefix, month - 1);
+ Map<String, double[]> out = new HashMap<>();
+ for (Map.Entry<String, double[]> e : cum.entrySet()) {
+ double[] prev = pre.get(e.getKey());
+ double[] d = new double[8];
+ for (int i = 0; i < 8; i++) {
+ d[i] = e.getValue()[i] - (prev == null ? 0 : prev[i]);
+ }
+ out.put(e.getKey(), d);
+ }
+ return out;
+ }
+
+ // ==================== 鍩庡競瀹㈣繍 鍏ㄧ渷姹囨�伙紙鍩庡競姹囨�籣妯℃澘锛� ====================
+
+ /** 鐢熸垚_鍩庡競瀹㈣繍姹囨��.xlsx锛堜互 鍩庡競姹囨�籣妯℃澘.xlsx 涓哄簳绋匡紱2026 娈靛~搴撳唴 1..N 鏈堢疮璁★紝鍚屾瘮娓呯┖锛�2025/2024 娈典繚鐣欐ā鏉垮巻鍙插弬鑰冨�硷級 */
+ public byte[] exportCityPassengerSummary(String period, String mode) throws Exception {
+ int year = Integer.parseInt(period.split("-")[0]);
+ int month = monthOf(period, mode);
+ double[] prov = loadCityPassengerCumulative(year + "-", month).getOrDefault("鍏ㄧ渷", new double[8]);
+ double busPax = prov[0], busTurn = prov[1];
+ double taxiPax = prov[2], taxiTurn = prov[3];
+ double railPax = prov[4], railTurn = prov[5];
+ double ferryPax = prov[6], ferryTurn = prov[7];
+ File template = resolveTemplate("鐢熸垚_鍩庡競瀹㈣繍姹囨��.xlsx");
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ dynamicTitle(sheet, year, month); // 鏍囬鎸夋姤琛ㄦ湡鍔ㄦ�佸寲
+ // 琛�3 鎬诲杩愰噺=鍏氦+鍑虹杞�(宸℃父+缃戠害杞�)+杞ㄩ亾+杞浮锛涜4 鍏氦锛涜5 鍑虹杞�=宸℃父+缃戠害杞︼紱琛�6 宸℃父锛涜7 缃戠害杞︼紱琛�8 杞ㄩ亾锛涜9 杞浮
+ setDataCell(sheet, 2, 1, busPax + taxiPax + railPax + ferryPax); // B3锛圥OI 0 鍩鸿2锛�
+ setDataCell(sheet, 2, 3, busTurn + taxiTurn + railTurn + ferryTurn); // D3
+ setDataCell(sheet, 3, 1, busPax); // B4 鍩庡競鍏氦
+ setDataCell(sheet, 3, 3, busTurn); // D4
+ setDataCell(sheet, 4, 1, taxiPax); // B5 鍩庡競鍑虹杞︼紙缃戠害杞︽棤婧愭暟鎹級
+ setDataCell(sheet, 4, 3, taxiTurn); // D5
+ setDataCell(sheet, 5, 1, taxiPax); // B6 鍏朵腑宸℃父鍑虹
+ setDataCell(sheet, 5, 3, taxiTurn); // D6
+ setZeroCell(sheet, 6, 1); // B7 鍩庡競缃戠害杞︼紙鏄惧紡 0锛宻etDataCell 瀵� 0 浼氱疆绌猴級
+ setZeroCell(sheet, 6, 3); // D7
+ setDataCell(sheet, 7, 1, railPax); // B8 杞ㄩ亾
+ setDataCell(sheet, 7, 3, railTurn); // D8
+ setDataCell(sheet, 8, 1, ferryPax); // B9 杞浮
+ setDataCell(sheet, 8, 3, ferryTurn);// D9
+ for (int r = 2; r <= 8; r++) { // 鍚屾瘮 C/E锛氭棤鍘诲勾鍚屾湡 鈫� 娓呯┖鏍蜂緥
+ setDataCell(sheet, r, 2, 0);
+ setDataCell(sheet, r, 4, 0);
+ }
+ // 搴曢儴鍗曟湀琛紙鏂扮増寮忥級锛氭爣棰樿11锛�0鍩�10锛夈�佹暟鎹13-19锛�0鍩�12-18锛夛紝濉綋鏈堝畬鎴愰噺
+ Row mTitle = sheet.getRow(10);
+ if (mTitle != null && mTitle.getCell(0) != null) {
+ mTitle.getCell(0).setCellValue(year + "骞�" + month + "鏈堝叏鐪佸畬鎴愬煄甯傚杩愰噺鎯呭喌");
+ }
+ double[] mProv = loadCityPassengerMonthMap(year + "-", month).getOrDefault("鍏ㄧ渷", new double[8]);
+ double mBusPax = mProv[0], mBusTurn = mProv[1];
+ double mTaxiPax = mProv[2], mTaxiTurn = mProv[3];
+ double mRailPax = mProv[4], mRailTurn = mProv[5];
+ double mFerryPax = mProv[6], mFerryTurn = mProv[7];
+ setDataCell(sheet, 12, 1, mBusPax + mTaxiPax + mRailPax + mFerryPax); // B13 鎬诲杩愰噺
+ setDataCell(sheet, 12, 3, mBusTurn + mTaxiTurn + mRailTurn + mFerryTurn); // D13 鎬诲懆杞噺
+ setDataCell(sheet, 13, 1, mBusPax); // B14 鍩庡競鍏氦
+ setDataCell(sheet, 13, 3, mBusTurn); // D14
+ setDataCell(sheet, 14, 1, mTaxiPax); // B15 鍩庡競鍑虹杞�
+ setDataCell(sheet, 14, 3, mTaxiTurn); // D15
+ setDataCell(sheet, 15, 1, mTaxiPax); // B16 鍏朵腑宸℃父鍑虹
+ setDataCell(sheet, 15, 3, mTaxiTurn); // D16
+ setZeroCell(sheet, 16, 1); // B17 鍩庡競缃戠害杞�
+ setZeroCell(sheet, 16, 3); // D17
+ setDataCell(sheet, 17, 1, mRailPax); // B18 杞ㄩ亾
+ setDataCell(sheet, 17, 3, mRailTurn); // D18
+ setDataCell(sheet, 18, 1, mFerryPax); // B19 杞浮
+ setDataCell(sheet, 18, 3, mFerryTurn);// D19
+ for (int r = 12; r <= 18; r++) { // 鍗曟湀琛� C/E 鍚屾瘮锛氭棤涓婂勾鍗曟湀婧� 鈫� 娓呯┖鏍蜂緥
+ setDataCell(sheet, r, 2, 0);
+ setDataCell(sheet, r, 4, 0);
+ }
+ recalc(wb);
+ clearFormulaErrorsAll(wb); // 鏃犲幓骞存暟鎹殑鍚屾瘮鍏紡 #DIV/0! 鈫� 娓呯┖
+ return toBytes(wb);
+ }
+ }
+
+ // ==================== 鍩庡競瀹㈣繍 鎶ヨ〃绯诲垪锛堜竴閿墦鍖咃級 ====================
+
+ /** 鐢熸垚_鍩庡競瀹㈣繍鎶ヨ〃绯诲垪.zip锛氬叕浜�/鍑虹/杞ㄩ亾杞浮鏄庣粏 + 鍒嗗競宸炵疮璁� + 鍚勫競宸炴槑缁嗚〃 + 姹囨�� */
+ public byte[] exportCityPassengerSeries(String period, String mode) throws Exception {
+ java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
+ try (java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(bos)) {
+ addZipEntry(zos, "鐢熸垚_鍩庡競鍏氦瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx", exportCityBusDetail(period, mode));
+ addZipEntry(zos, "鐢熸垚_宸℃父鍑虹瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx", exportCityTaxiDetail(period, mode));
+ addZipEntry(zos, "鐢熸垚_杞ㄩ亾杞浮瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx", exportCityRailFerryDetail(period, mode));
+ addZipEntry(zos, "鐢熸垚_鍩庡競瀹㈣繍瀹㈣繍閲忓垎甯傚窞绱.xlsx", exportCityPassengerCitySum("鐢熸垚_鍩庡競瀹㈣繍瀹㈣繍閲忓垎甯傚窞绱.xlsx", period, mode));
+ addZipEntry(zos, "鐢熸垚_鍩庡競瀹㈣繍鍚勫競宸炴槑缁嗚〃.xlsx", exportCityPassengerCitySum("鐢熸垚_鍩庡競瀹㈣繍鍚勫競宸炴槑缁嗚〃.xlsx", period, mode));
+ addZipEntry(zos, "鐢熸垚_鍩庡競瀹㈣繍姹囨��.xlsx", exportCityPassengerSummary(period, mode));
+ }
+ return bos.toByteArray();
+ }
+
+ /** 鐢熸垚_璐ц繍鎶ヨ〃绯诲垪.zip锛氳揣杩愰噺鍒嗗競宸炴槑缁� + 璐ц繍閲忔帓鍚� + 鍛ㄨ浆閲忔帓鍚� */
+ public byte[] exportFreightSeries(String period, String mode) throws Exception {
+ java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
+ try (java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(bos)) {
+ addZipEntry(zos, "鐢熸垚_璐ц繍閲忓垎甯傚窞鏄庣粏.xlsx", exportCityDetail(period, mode));
+ addZipEntry(zos, "鐢熸垚_璐ц繍閲忔帓鍚�.xlsx", exportFreightRank(period, mode));
+ addZipEntry(zos, "鐢熸垚_鍛ㄨ浆閲忔帓鍚�.xlsx", exportTurnoverRank(period, mode));
+ }
+ return bos.toByteArray();
+ }
+
+ /** 鐢熸垚_鍏矾鏃呭鎶ヨ〃绯诲垪.zip锛氬垎甯傚窞鏄庣粏 + 涓彛寰勬槑缁�/鎺掑悕/鍒嗘瀽 */
+ public byte[] exportPassengerSeries(String period, String mode) throws Exception {
+ java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
+ try (java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(bos)) {
+ addZipEntry(zos, "鐢熸垚_鍏矾鏃呭鍒嗗競宸�.xlsx", exportPassengerCityDetail(period, mode));
+ addZipEntry(zos, "鐢熸垚_涓彛寰勬槑缁�.xlsx", exportPassengerMidDetail(period, mode));
+ addZipEntry(zos, "鐢熸垚_涓彛寰勬帓鍚�.xlsx", exportPassengerMidRank(period, mode));
+ addZipEntry(zos, "鐢熸垚_涓彛寰勫垎鏋�.xlsx", exportPassengerMidAnalysis(period, mode));
+ }
+ return bos.toByteArray();
+ }
+
+ /**
+ * 鐢熸垚_閬撹矾杩愯緭閲忔眹鎬昏〃.xlsx锛圥0-P1 楠ㄦ灦锛夛細鏁存湰澶嶅埗姣嶇増銆奩YYY骞碝鏈堥亾璺繍杈撻噺姹囨�昏〃.xlsx銆嬶紝
+ * 淇濈暀鍏ㄩ儴椤电/鐗堝紡/鍏紡/2025 骞寸紦瀛樺�硷紝浠呮妸琛ㄥご骞翠唤鍔ㄦ�佸寲涓虹洰鏍囧勾锛涙暟鎹~鍏呮寜 P2 璧烽�愭鎺ュ叆銆�
+ */
+ public byte[] exportSummaryWorkbook(String period, String mode) throws Exception {
+ return exportSummaryWorkbook(period, mode, null);
+ }
+
+ /** 鐢熸垚_閬撹矾杩愯緭閲忔眹鎬昏〃.xlsx锛圥0-P1 楠ㄦ灦锛屾敮鎸� toMonth 瑁佸壀锛夛細
+ * 浠ャ�奩YYY骞碝鏈堥亾璺繍杈撻噺姹囨�昏〃.xlsx銆嬶紙M 鐢� period 鍐冲畾锛変负姣嶇増锛屾寜鍚屾湡澶囦唤姣嶇増杩樺師鏈堝害鍧楋紱
+ * toMonth 闈炵┖涓斿皬浜� M 鏃讹紝鎶� 8 涓彴璐�/鍚堟垚椤佃鍒� toMonth 鏈堬紙toMonth+1..M 鐨勫綋鏈堝��/鍚屾瘮鍒楁竻绌恒�佷繚鐣欒〃澶达紝
+ * 绱涓庣疮璁″悓姣斿叕寮忔敼涓烘寜 toMonth 鏈堥噸绠楋級锛岀敤浜庘�滃厛鐢熸垚 1-6 鏈堛��1-7 鏈堟墿鍒椻�濋獙璇併�� */
+ public byte[] exportSummaryWorkbook(String period, String mode, Integer toMonth) throws Exception {
+ int year = Integer.parseInt(period.contains("-") ? period.split("-")[0] : period);
+ int month = period.contains("-") ? monthOf(period, mode) : 12;
+ File template = resolveSummaryMother(period, mode);
+ if (template == null) {
+ throw new RuntimeException("鏈壘鍒版眹鎬昏〃姣嶇増銆�" + year + "骞�" + month + "鏈堥亾璺繍杈撻噺姹囨�昏〃.xlsx銆嬶紙docs/鐢熸垚姹囨�诲ぇ琛級");
+ }
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ File donor = resolveSummaryDonor(year, month);
+ if (donor != null) {
+ try (InputStream din = new FileInputStream(donor); XSSFWorkbook dwb = new XSSFWorkbook(din)) {
+ int restored = restoreSummaryMonthlyBlocks(wb, dwb);
+ log.info("姹囨�诲伐浣滅翱鏈堝害鍧楄繕鍘熷畬鎴愶紝琛ラ綈/瑕嗙洊鍗曞厓鏍兼暟={}锛堟瘝鐗堬細{}锛屽浠芥瘝鐗堬細{}锛�", restored, template.getName(), donor.getName());
+ }
+ } else {
+ log.warn("姹囨�诲伐浣滅翱鏈壘鍒板悓鏈熷浠芥瘝鐗堬紙_澶囦唤_{}骞磠}鏈堚�︼級锛岃緭鍑哄皢淇濇寔姣嶇増鐜扮姸锛堝彲鑳戒负 1-4 鏈堥鏋讹級", year, month);
+ }
+ if (toMonth != null && toMonth > 0 && toMonth < month) {
+ int trimmed = trimSummaryMonthlySheets(wb, toMonth);
+ log.info("姹囨�诲伐浣滅翱瑁佸壀鑷� {} 鏈堝畬鎴愶紝娓呯┖/鏀瑰啓鍗曞厓鏍兼暟={}", toMonth, trimmed);
+ }
+ dynamicSummaryYear(wb, year);
+ applyTwoDecimalFormat(wb); // 姹囨�诲ぇ琛ㄤ繚鐣欎汉宸ユ瘝鐗堝垪瀹�/鐗堝紡锛氫笉鍋� autoFit锛堥暱鍏紡浼氭妸鍒楀椤剁垎锛�
+ if (!wb.getCTWorkbook().isSetCalcPr()) wb.getCTWorkbook().addNewCalcPr();
+ wb.getCTWorkbook().getCalcPr().setFullCalcOnLoad(true); // 杩樺師/鏀瑰啓鍏紡鍚庢墦寮�鍗抽噸绠�
+ return toBytes(wb);
+ }
+ }
+
+ /** 姹囨�昏〃姣嶇増瀹氫綅锛氫粎绮剧‘鍖归厤 {year}骞磠month}鏈堚�︼紙P0-P1 楠ㄦ灦鏈熶笉鍏佽璺ㄦ湀/璺ㄥ勾闈欓粯鍥為��锛�
+ * 鐩爣鏈熸棤瀵瑰簲姣嶇増鏃舵槑纭姤閿欙紝鏈堜唤鎵╁睍瑙勫垯寰� P0 姣嶇増瀹氱鍚庡啀鏀惧紑锛� */
+ private File resolveSummaryMother(String period, String mode) throws Exception {
+ String year = period != null && period.contains("-") ? period.split("-")[0] : (period == null ? "" : period);
+ int month = period != null && period.contains("-") ? monthOf(period, mode) : 12;
+ String name = year + "骞�" + month + "鏈堥亾璺繍杈撻噺姹囨�昏〃.xlsx";
+ return resolveAnyTemplate(summaryTemplateDir, name);
+ }
+
+ // ==================== 缃戠害杞﹀杩愰噺鎷嗗垎琛紙鏈堝害锛� ====================
+
+ /** 缃戠害杞﹀杩愰噺鎷嗗垎琛細杈撳叆=閮ㄧ骇璁㈠崟锛堢綉绾﹁溅璁㈠崟鍙婂叏鐪佹�婚噺.xlsx G-W锛�+ 鍏ㄧ渷 pin锛圔-E锛�+ 宸℃父鍑虹鏈堟姤锛圖B锛夛紱
+ * 绠楁硶涓庛�婄綉绾﹁溅鎷嗗垎.xlsx銆嬫湀椤典竴鑷达細瀹㈣繍閲�=璁㈠崟鍗犳瘮脳鍏ㄧ渷鎬婚噺锛涘煄甯傚唴=宸℃父鍑虹鍩庡競鍐呭崰姣斾唬鐞嗐�佹姹変繚鎸佽嚜韬叾浣欐寜鍓╀綑鍒嗘憡锛�
+ * 鍛ㄨ浆閲�=瀹㈣繍閲徝楀贰娓稿嚭绉熷钩鍧囪繍璺濆崰姣斿垎鎽婂叏鐪佸懆杞噺 pin锛屽煄甯傚唴鍛ㄨ浆閲忓悓娉曘�� */
+ public byte[] exportWycSplit(String period, String mode) throws Exception {
+ if (period == null || !period.contains("-")) {
+ throw new RuntimeException("缃戠害杞﹀杩愰噺鎷嗗垎琛ㄤ粎鏀寔鎸夋湀鐢熸垚锛岃閫夋嫨鍏蜂綋鏈堜唤");
+ }
+ int year = Integer.parseInt(period.split("-")[0]);
+ int month = parseMonth(period);
+ Map<String, Object> inp = loadWycMonthlyInput(period, mode);
+ if (inp == null) {
+ throw new RuntimeException("銆婄綉绾﹁溅璁㈠崟鍙婂叏鐪佹�婚噺.xlsx銆嬬己灏戞姤琛ㄦ湡 " + period + " 鐨勬暟鎹锛岃鍏堢淮鎶ゅ綋鏈堣鍗曚笌鍏ㄧ渷 pin");
+ }
+ double pinK = (Double) inp.get("pinK");
+ double pinCK = (Double) inp.get("pinCK");
+ double pinZ = (Double) inp.get("pinZ");
+ double pinCZ = (Double) inp.get("pinCZ");
+ double orderSum = (Double) inp.get("orderSum");
+ double[] orderArr = (double[]) inp.get("orders");
+ if (pinK <= 0 || pinCK <= 0 || pinZ <= 0 || pinCZ <= 0 || orderSum <= 0) {
+ throw new RuntimeException("缃戠害杞﹁緭鍏� " + period + " 琛屼笉瀹屾暣锛氬叏鐪� pin / 璁㈠崟缂哄け锛岃鏍稿銆婄綉绾﹁溅璁㈠崟鍙婂叏鐪佹�婚噺.xlsx銆�");
+ }
+ List<String> cities = RegionUtil.cityList();
+ int n = cities.size();
+ if (orderArr == null || orderArr.length < n) {
+ throw new RuntimeException("缃戠害杞﹁鍗曞垪鏁颁笉瓒筹紙搴斾负 17 甯傚窞璁㈠崟鍒楋級");
+ }
+ Map<String, double[]> taxi = taxiMonthlyOf(period);
+ java.util.List<String> missingTaxi = new java.util.ArrayList<>();
+ double[] Dtax = new double[n];
+ double[] Etax = new double[n];
+ double[] avgD = new double[n];
+ double[] avgDc = new double[n];
+ for (int i = 0; i < n; i++) {
+ double[] a = taxi.get(cities.get(i));
+ if (a == null || a[0] <= 0) {
+ missingTaxi.add(cities.get(i));
+ continue;
+ }
+ Dtax[i] = a[0];
+ Etax[i] = a[2];
+ avgD[i] = a[4];
+ avgDc[i] = a[5];
+ }
+ if (!missingTaxi.isEmpty()) {
+ throw new RuntimeException("宸℃父鍑虹鏈堟姤缂哄皯浠ヤ笅甯傚窞鏁版嵁锛�" + String.join("銆�", missingTaxi));
+ }
+ double[] C = new double[n];
+ double[] H = new double[n];
+ double[] I = new double[n];
+ double[] Gl = new double[n];
+ double[] Hl = new double[n];
+ double[] Il = new double[n];
+ double sumG = 0;
+ double sumDl = 0;
+ double sumEl = 0;
+ for (int i = 0; i < n; i++) {
+ C[i] = orderArr[i] / orderSum * pinK;
+ double F = Etax[i] / Dtax[i];
+ double G = C[i] * F;
+ sumG += G;
+ double Dl = C[i] * avgD[i];
+ double El = H[i] * avgDc[i];
+ sumDl += Dl;
+ sumEl += El;
+ }
+ // 鍩庡競鍐咃細姝︽眽淇濇寔鑷韩锛屽叾浣欐寜 G 鍓╀綑鍗犳瘮鍒嗘憡鑷冲叏鐪佸煄甯傚唴 pin
+ for (int i = 0; i < n; i++) {
+ if (i == 0) {
+ H[i] = C[i] * (Etax[i] / Dtax[i]);
+ } else {
+ H[i] = (C[i] * (Etax[i] / Dtax[i])) / (sumG - C[0] * (Etax[0] / Dtax[0])) * (pinCK - C[0] * (Etax[0] / Dtax[0]));
+ }
+ I[i] = C[i] - H[i];
+ }
+ // 鍛ㄨ浆閲忥細鎸� 瀹㈣繍閲徝楀贰娓稿嚭绉熷钩鍧囪繍璺� 鍗犳瘮鍒嗘憡鍏ㄧ渷鍛ㄨ浆閲� pin
+ double whG = C[0] * (Etax[0] / Dtax[0]);
+ double whDl = C[0] * avgD[0];
+ double[] El2 = new double[n];
+ double sumEl2 = 0;
+ for (int i = 0; i < n; i++) {
+ double Dl = C[i] * avgD[i];
+ double El2v = H[i] * avgDc[i];
+ El2[i] = El2v;
+ sumEl2 += El2v;
+ Gl[i] = Dl / sumDl * pinZ;
+ }
+ for (int i = 0; i < n; i++) {
+ if (i == 0) {
+ Hl[i] = Gl[i];
+ } else {
+ Hl[i] = El2[i] / (sumEl2 - El2[0]) * (pinCZ - Gl[0]);
+ }
+ Il[i] = Gl[i] - Hl[i];
+ }
+ return writeWycSplitWorkbook(period, cities, orderArr, C, Dtax, Etax, H, I, avgD, avgDc, Gl, Hl, Il, pinK, pinCK, pinZ, pinCZ, orderSum);
+ }
+
+ private byte[] writeWycSplitWorkbook(String period, List<String> cities, double[] orders, double[] C, double[] Dtax,
+ double[] Etax, double[] H, double[] I, double[] avgD, double[] avgDc,
+ double[] Gl, double[] Hl, double[] Il,
+ double pinK, double pinCK, double pinZ, double pinCZ, double orderSum) throws Exception {
+ XSSFWorkbook wb = new XSSFWorkbook();
+ XSSFSheet sh = wb.createSheet(period + "鎷嗗垎");
+ int n = cities.size();
+ // 瀹㈣繍閲忓潡
+ Row t = sh.createRow(0);
+ t.createCell(0).setCellValue("缃戠害杞﹀杩愰噺鎷嗗垎锛堜竾浜猴級 鎶ヨ〃鏈燂細" + period);
+ String[] head1 = {"甯傚窞", "璁㈠崟鎬绘暟锛堝崟锛�", "缃戠害杞﹀杩愰噺锛堜竾浜猴級", "宸℃父鍑虹瀹㈣繍閲忥紙涓囦汉锛�", "宸℃父鍑虹鍩庡競鍐呭杩愰噺锛堜竾浜猴級", "鍩庡競鍐呭崰姣�", "缃戠害杞﹀煄甯傚唴瀹㈣繍閲忥紙涓囦汉锛�", "缃戠害杞﹀煄闄呭煄涔″杩愰噺锛堜竾浜猴級"};
+ Row h1 = sh.createRow(1);
+ for (int j = 0; j < head1.length; j++) h1.createCell(j).setCellValue(head1[j]);
+ int r = 2;
+ writeWycRow(sh, r++, "鍏ㄧ渷", orderSum, pinK, sum(Dtax), sum(Etax), pinK > 0 ? pinCK / pinK : 0, pinCK, pinK - pinCK);
+ for (int i = 0; i < n; i++) {
+ writeWycRow(sh, r++, cities.get(i), orders[i], C[i], Dtax[i], Etax[i], Dtax[i] > 0 ? Etax[i] / Dtax[i] : 0, H[i], I[i]);
+ }
+ r += 1;
+ Row t2 = sh.createRow(r++);
+ t2.createCell(0).setCellValue("鏃呭鍛ㄨ浆閲忔媶鍒嗭紙涓囦汉鍏噷锛�");
+ String[] head2 = {"甯傚窞", "鍑虹杞﹀钩鍧囪繍璺濓紙鍏噷锛�", "鍑虹杞﹀煄甯傚唴骞冲潎杩愯窛锛堝叕閲岋級", "缃戠害杞︽梾瀹㈠懆杞噺锛堜竾浜哄叕閲岋級", "缃戠害杞﹀煄甯傚唴鏃呭鍛ㄨ浆閲忥紙涓囦汉鍏噷锛�", "缃戠害杞﹀煄闄呭煄涔℃梾瀹㈠懆杞噺锛堜竾浜哄叕閲岋級"};
+ Row h2 = sh.createRow(r++);
+ for (int j = 0; j < head2.length; j++) h2.createCell(j).setCellValue(head2[j]);
+ writeWycRow2(sh, r++, "鍏ㄧ渷", 0, 0, pinZ, pinCZ, pinZ - pinCZ);
+ for (int i = 0; i < n; i++) {
+ writeWycRow2(sh, r++, cities.get(i), avgD[i], avgDc[i], Gl[i], Hl[i], Il[i]);
+ }
+ r += 1;
+ String[] notes = {
+ "娉細1) 瀹㈣繍閲� C = 璁㈠崟鍗犳瘮 脳 鍏ㄧ渷缃戠害杞﹀杩愰噺锛涘煄甯傚唴 H锛氭姹�=鑷韩锛屽叾浣欐寜 G 鍓╀綑鍗犳瘮鍒嗘憡鑷冲叏鐪佸煄甯傚唴 pin锛涘煄闄呭煄涔� = 鎬婚噺 - 鍩庡競鍐呫��",
+ " 2) 鍛ㄨ浆閲� G = 瀹㈣繍閲� 脳 宸℃父鍑虹骞冲潎杩愯窛 鐨勫崰姣� 脳 鍏ㄧ渷缃戠害杞﹀懆杞噺 pin锛涘煄甯傚唴鍛ㄨ浆閲忓悓娉曪紙鐢ㄥ煄甯傚唴骞冲潎杩愯窛锛夈��",
+ " 3) 杈撳叆锛氳鍗� = 褰撴湀鍒嗘瀽鎶ュ憡闄勪欢1锛�17 甯傚窞璁㈠崟鏁帮級锛涘叏鐪� pin = 缃戠害杞︽�绘暟.xlsx锛涘贰娓稿嚭绉� = 宸℃父鍑虹鏈堟姤锛堢郴缁熷鍏ワ紝鍚钩鍧囪繍璺濓級銆�",
+ " 4) 姝︽眽鏃犲煄闄呭煄涔★紱鏁板�间繚鐣欏叏绮惧害锛岀晫闈�/鏂囦欢鏄剧ず涓や綅灏忔暟銆�"
+ };
+ for (String nt : notes) {
+ Row nr = sh.createRow(r++);
+ nr.createCell(0).setCellValue(nt);
+ }
+ for (int j = 0; j < 8; j++) sh.setColumnWidth(j, 18 * 256);
+ return toBytes(wb);
+ }
+
+ private void writeWycRow(Sheet sh, int r, String name, double ord, double k, double dt, double et, double f, double h, double i) {
+ Row row = sh.createRow(r);
+ row.createCell(0).setCellValue(name);
+ row.createCell(1).setCellValue(ord);
+ row.createCell(2).setCellValue(k);
+ row.createCell(3).setCellValue(dt);
+ row.createCell(4).setCellValue(et);
+ row.createCell(5).setCellValue(f);
+ row.createCell(6).setCellValue(h);
+ row.createCell(7).setCellValue(i);
+ }
+
+ private void writeWycRow2(Sheet sh, int r, String name, double ad, double adc, double g, double h, double i) {
+ Row row = sh.createRow(r);
+ row.createCell(0).setCellValue(name);
+ row.createCell(1).setCellValue(ad);
+ row.createCell(2).setCellValue(adc);
+ row.createCell(3).setCellValue(g);
+ row.createCell(4).setCellValue(h);
+ row.createCell(5).setCellValue(i);
+ }
+
+ private double sum(double[] a) {
+ double s = 0;
+ for (double v : a) s += v;
+ return s;
+ }
+
+ /** 璇诲彇 docs/鍩庡競瀹㈣繍/缃戠害杞﹁鍗曞強鍏ㄧ渷鎬婚噺.xlsx锛氭寜 period(yyyy-MM) 琛屽彇 pin(B-E) 涓� 17 甯傚窞璁㈠崟(G-W) */
+ private Map<String, Object> loadWycMonthlyInput(String period, String mode) throws Exception {
+ String target = period;
+ File f;
+ try {
+ f = resolveAnyTemplate(templateDir, "缃戠害杞﹁鍗曞強鍏ㄧ渷鎬婚噺.xlsx");
+ } catch (Exception e) {
+ throw new RuntimeException("鏈壘鍒般�婄綉绾﹁溅璁㈠崟鍙婂叏鐪佹�婚噺.xlsx銆嬶紝璇锋斁鍒� docs/鍩庡競瀹㈣繍 鐩綍");
+ }
+ try (InputStream in = new FileInputStream(f);
+ org.apache.poi.ss.usermodel.Workbook wb = org.apache.poi.ss.usermodel.WorkbookFactory.create(in)) {
+ org.apache.poi.ss.usermodel.Sheet sh = wb.getSheetAt(0);
+ org.apache.poi.ss.usermodel.DataFormatter df = new org.apache.poi.ss.usermodel.DataFormatter();
+ List<String> cities = RegionUtil.cityList();
+ int n = cities.size();
+ for (int i = 1; i <= sh.getLastRowNum(); i++) {
+ Row row = sh.getRow(i);
+ if (row == null) continue;
+ Cell c0 = row.getCell(0);
+ if (c0 == null) continue;
+ String m = df.formatCellValue(c0).trim();
+ if (m == null || m.isEmpty()) continue;
+ if (m.length() > 7) m = m.substring(0, 7);
+ if (!target.equals(m)) continue;
+ Map<String, Object> map = new HashMap<>();
+ map.put("pinK", cellNum(row, 1, df, 0.0));
+ map.put("pinCK", cellNum(row, 2, df, 0.0));
+ map.put("pinZ", cellNum(row, 3, df, 0.0));
+ map.put("pinCZ", cellNum(row, 4, df, 0.0));
+ double[] orders = new double[n];
+ double orderSum = 0;
+ for (int k = 0; k < n; k++) {
+ orders[k] = cellNum(row, 6 + k, df, 0.0);
+ orderSum += orders[k];
+ }
+ if (orderSum <= 0) {
+ orderSum = cellNum(row, 5, df, 0.0); // F 鍒楀悎璁″厹搴�
+ }
+ map.put("orders", orders);
+ map.put("orderSum", orderSum);
+ return map;
+ }
+ return null;
+ }
+ }
+
+ private double cellNum(Row row, int idx, org.apache.poi.ss.usermodel.DataFormatter df, double def) {
+ Cell c = row.getCell(idx);
+ if (c == null) return def;
+ if (c.getCellType() == CellType.NUMERIC) return c.getNumericCellValue();
+ String s = df.formatCellValue(c).replace(",", "").trim();
+ if (s == null || s.isEmpty()) return def;
+ try {
+ return Double.parseDouble(s);
+ } catch (Exception e) {
+ return def;
+ }
+ }
+
+ /** 宸℃父鍑虹鏈堟姤锛圖B锛夋寜鏈堝姞杞斤細甯傚窞 -> [瀹㈣繍閲�, 鍛ㄨ浆閲�, 鍩庡競鍐呭杩愰噺, 鍩庡競鍐呭懆杞噺, 骞冲潎杩愯窛, 鍩庡競鍐呭钩鍧囪繍璺漖 */
+ private Map<String, double[]> taxiMonthlyOf(String period) {
+ Map<String, double[]> map = new java.util.LinkedHashMap<>();
+ List<CityTaxiMonthly> rows = cityTaxiMapper.selectList(
+ new LambdaQueryWrapper<CityTaxiMonthly>().eq(CityTaxiMonthly::getReportPeriod, period));
+ for (CityTaxiMonthly r : rows) {
+ String city = RegionUtil.normalizeCityName(r.getCity());
+ if (city == null || city.isEmpty()) city = "鏈煡";
+ double[] a = map.computeIfAbsent(city, k -> new double[6]);
+ a[0] += nz(r.getPassengerVolume());
+ a[1] += nz(r.getTurnover());
+ a[2] += nz(r.getPassengerCity());
+ a[3] += nz(r.getTurnoverCity());
+ if (r.getAvgDistance() != null && r.getAvgDistance() > 0) a[4] = r.getAvgDistance();
+ if (r.getAvgDistanceCity() != null && r.getAvgDistanceCity() > 0) a[5] = r.getAvgDistanceCity();
+ }
+ for (double[] a : map.values()) {
+ if (a[4] <= 0 && a[0] > 0) a[4] = round(a[1] / a[0], 2);
+ if (a[5] <= 0 && a[2] > 0) a[5] = round(a[3] / a[2], 2);
+ }
+ return map;
+ }
+
+ /** 瀹氫綅鍚屾湡澶囦唤姣嶇増锛堟竻鐞嗗墠鐨勫畬鏁存湀姣嶇増锛夛紝鐢ㄤ簬鎶婇鏋舵瘝鐗堢己澶辩殑 5-7 鏈堟湀搴﹀潡鎸夊浠借繕鍘燂紱
+ * 涓� resolveAnyTemplate 鐩稿悓绛栫暐锛氬湪閰嶇疆鐩綍銆乽ser.dir 鐩稿鐩綍銆佷笂绾х洰褰曚笁涓�欓�夋牴涓壂鎻� */
+ private File resolveSummaryDonor(int year, int month) {
+ String rel = summaryTemplateDir;
+ while (rel.startsWith("./")) rel = rel.substring(2);
+ String[] roots = {
+ summaryTemplateDir,
+ System.getProperty("user.dir") + "/" + rel,
+ System.getProperty("user.dir") + "/../" + rel
+ };
+ for (String root : roots) {
+ if (root == null || root.trim().isEmpty()) continue;
+ File dir = new File(root);
+ File[] files = dir.listFiles((d, name) ->
+ name.startsWith("_澶囦唤_") && name.contains(year + "骞�" + month + "鏈�") && name.contains("閬撹矾杩愯緭閲忔眹鎬昏〃"));
+ if (files != null && files.length > 0) return files[0];
+ }
+ return null;
+ }
+
+ /** 鎸夊悓鏈熷浠芥瘝鐗堣繕鍘熸湀搴﹀潡锛氬嚒澶囦唤鏈夊唴瀹硅�屾瘝鐗堝悓鏍肩己澶�/鍐呭涓嶅悓锛堟竻鐞嗘椂琚鎺夌殑 5-7 鏈堝�间笌绱鍏紡锛夌殑鍗曞厓鏍硷紝鏁存牸鍥炲~骞惰鐩� */
+ private int restoreSummaryMonthlyBlocks(XSSFWorkbook wb, XSSFWorkbook donor) {
+ int restored = 0;
+ for (int i = 0; i < donor.getNumberOfSheets(); i++) {
+ Sheet ds = donor.getSheetAt(i);
+ if (ds == null) continue;
+ Sheet bs = wb.getSheet(ds.getSheetName());
+ if (bs == null) continue;
+ for (int r = ds.getFirstRowNum(); r <= ds.getLastRowNum(); r++) {
+ Row dr = ds.getRow(r);
+ if (dr == null) continue;
+ Row br = bs.getRow(r);
+ for (Cell dc : dr) {
+ if (dc == null) continue;
+ CellType t = dc.getCellType();
+ if (t == CellType.BLANK) continue;
+ String dtx = summaryCellText(dc);
+ if (dtx == null || dtx.isEmpty()) continue;
+ Cell bc = (br == null) ? null : br.getCell(dc.getColumnIndex());
+ if (bc != null && dtx.equals(summaryCellText(bc))) continue;
+ Row tr = (bc != null) ? br : bs.getRow(r);
+ if (tr == null) tr = bs.createRow(r);
+ Cell tc = (bc != null) ? bc : tr.getCell(dc.getColumnIndex());
+ if (tc == null) tc = tr.createCell(dc.getColumnIndex());
+ tc.setBlank();
+ if (t == CellType.FORMULA) {
+ String f = dc.getCellFormula();
+ if (f != null) tc.setCellFormula(f);
+ } else if (t == CellType.STRING) {
+ tc.setCellValue(dc.getStringCellValue());
+ } else if (t == CellType.NUMERIC) {
+ tc.setCellValue(dc.getNumericCellValue());
+ } else if (t == CellType.BOOLEAN) {
+ tc.setCellValue(dc.getBooleanCellValue());
+ }
+ restored++;
+ }
+ }
+ }
+ return restored;
+ }
+
+ /** 鍗曞厓鏍煎唴瀹规枃鏈寲锛堝叕寮忓甫 = 鍓嶇紑锛夛紝鐢ㄤ簬璺ㄧ翱姣斿 */
+ private String summaryCellText(Cell c) {
+ if (c == null) return null;
+ switch (c.getCellType()) {
+ case FORMULA: {
+ String f = c.getCellFormula();
+ return f == null ? "" : "=" + f;
+ }
+ case STRING:
+ return c.getStringCellValue();
+ case NUMERIC:
+ return Double.toString(c.getNumericCellValue());
+ case BOOLEAN:
+ return Boolean.toString(c.getBooleanCellValue());
+ default:
+ return "";
+ }
+ }
+
+ /** 鎶� 8 涓彴璐�/鍚堟垚椤佃鍓埌 keepMonths 鏈堬細
+ * 鏈堝害鍊煎垪 2026 骞� m 鏈� = 绗� 3+2*(m-1) 鍒楋紙C/E/G/I/K/M/O锛夛紝鍚屾瘮鍒椾负鍏跺悗涓�鍒楋紱
+ * 绱 Q 鍒� = C+E+...+O锛岀疮璁″悓姣� R 鍒楀垎姣� = 2025 骞村悓鏈堝垪 T/V/X/Z/AB/AD/AF銆�
+ * 瑁佸壀 = 鏁版嵁琛岋紙鍚疮璁″叕寮忎笖浠讳竴 2026 鏈堝害鍒楁湁鍐呭锛変腑 keepMonths+1..7 鏈堢殑褰撴湀鍊�/鍚屾瘮鍗曞厓鏍兼竻绌猴紙琛ㄥご淇濈暀锛夛紝
+ * 骞舵妸璇ヨ绱鍏紡鍘绘帀瀵瑰簲 +鍒楋紝绱鍚屾瘮鍒嗘瘝鍘绘帀瀵瑰簲 2025 鍒椼�� */
+ private int trimSummaryMonthlySheets(XSSFWorkbook wb, int keepMonths) {
+ String[] scope = {" 璐ц繍", "鐝嚎鍖呰溅", "鍩庡競瀹㈣繍", "鍏氦", "鍑虹", "缃戠害杞�", "杞ㄩ亾銆佽疆娓�", "涓彛寰勬槑缁�"};
+ java.util.Set<String> scopeSet = new java.util.HashSet<>();
+ for (String s : scope) scopeSet.add(s);
+ int touched = 0;
+ for (int i = 0; i < wb.getNumberOfSheets(); i++) {
+ Sheet sh = wb.getSheetAt(i);
+ if (sh == null || !scopeSet.contains(sh.getSheetName())) continue;
+ for (int r = sh.getFirstRowNum(); r <= sh.getLastRowNum(); r++) {
+ Row row = sh.getRow(r);
+ if (row == null) continue;
+ Cell q = row.getCell(16); // Q 鍒� = 绱
+ if (q == null || q.getCellType() != CellType.FORMULA) continue;
+ boolean hasMonthly = false;
+ for (int m = 1; m <= 7 && !hasMonthly; m++) {
+ Cell v = row.getCell(2 + 2 * (m - 1)); // C,E,G,I,K,M,O
+ if (v != null && v.getCellType() != CellType.BLANK) hasMonthly = true;
+ }
+ if (!hasMonthly) continue; // 鎺掗櫎椤甸/椤典腑璺ㄩ〉绛炬牎楠屽叕寮忚锛堟棤鏈堝害鍊硷級
+ int excelRow = r + 1; // 鍏紡鍐呭紩鐢ㄤ负 Excel 1-based 琛屽彿
+ for (int m = keepMonths + 1; m <= 7; m++) {
+ int valueCol = 2 + 2 * (m - 1); // 2026 褰撴湀鍊煎垪
+ int yoyCol = valueCol + 1; // 褰撴湀鍚屾瘮鍒�
+ String vLetter = colLetter(valueCol);
+ Cell vc = row.getCell(valueCol);
+ if (vc != null) {
+ vc.setBlank();
+ touched++;
+ }
+ Cell yc = row.getCell(yoyCol);
+ if (yc != null) {
+ yc.setBlank();
+ touched++;
+ }
+ String fq = q.getCellFormula();
+ if (fq != null && fq.contains("+" + vLetter + excelRow)) {
+ q.setCellFormula(fq.replace("+" + vLetter + excelRow, ""));
+ touched++;
+ }
+ Cell rc = row.getCell(17); // R 鍒� = 绱鍚屾瘮
+ if (rc != null && rc.getCellType() == CellType.FORMULA) {
+ String fr = rc.getCellFormula();
+ int lastCol = 19 + 2 * (m - 1); // 2025 鍚屾湀鍒� T..AF锛�0-based锛歍=19,AF=31锛�
+ String lLetter = colLetter(lastCol);
+ String txt = fr;
+ if (txt != null && txt.contains("," + lLetter + excelRow)) {
+ txt = txt.replace("," + lLetter + excelRow, "");
+ touched++;
+ }
+ if (txt != null && txt.contains("+" + lLetter + excelRow)) {
+ txt = txt.replace("+" + lLetter + excelRow, "");
+ touched++;
+ }
+ if (txt != null && !txt.equals(fr)) rc.setCellFormula(txt);
+ }
+ }
+ }
+ }
+ return touched;
+ }
+
+ /** 姹囨�诲伐浣滅翱骞翠唤鍔ㄦ�佸寲锛氫粎鎶� 2026骞� 鍓嶇紑鏇挎崲涓虹洰鏍囧勾锛�2025/2024 鍙傝�冨垪涓嶅姩锛� */
+ private void dynamicSummaryYear(XSSFWorkbook wb, int year) {
+ String oldPrefix = "2026骞�";
+ String newPrefix = year + "骞�";
+ if (oldPrefix.equals(newPrefix)) return;
+ for (int i = 0; i < wb.getNumberOfSheets(); i++) {
+ Sheet sh = wb.getSheetAt(i);
+ if (sh == null) continue;
+ for (Row row : sh) {
+ if (row == null) continue;
+ for (Cell c : row) {
+ if (c == null || c.getCellType() != CellType.STRING) continue;
+ String v = c.getStringCellValue();
+ if (v != null && v.contains(oldPrefix)) {
+ c.setCellValue(v.replace(oldPrefix, newPrefix));
+ }
+ }
+ }
+ }
+ }
+
+ /** 鐢熸垚_鎶曡祫鎶ヨ〃绯诲垪.zip锛氶瀹夋帓 + 鍗佷簲浜� + 浜垮厓 + 缁忔祹寮哄幙 */
+ public byte[] exportInvestSeries(String period, String mode) throws Exception {
+ java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
+ try (java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(bos)) {
+ addZipEntry(zos, "鐢熸垚_鍏ㄧ渷棰勫畨鎺掕鍒掕繘搴︽儏鍐垫眹鎬�.xls", investPlan(period, mode));
+ addZipEntry(zos, "鐢熸垚_鍗佷簲浜旇鍒掔墿娴侀」鐩繘灞曟儏鍐�.xls", investFiveYearLogistics(period, mode));
+ addZipEntry(zos, "鐢熸垚_婀栧寳鐪侊紙瀹㈣揣绔欏満锛変嚎鍏冩姇璧勯」鐩�.xls", investBillion(period, mode));
+ addZipEntry(zos, "鐢熸垚_缁忔祹寮哄幙浜ら�氱墿娴佸熀纭�璁炬柦鎶曡祫缁熻鎶ヨ〃.xls", investCounty(period, mode));
+ }
+ return bos.toByteArray();
+ }
+
+ /** 鐢熸垚_鎵�閫夋姤琛�.zip锛氭寜 type 鍒楄〃鎵撳寘锛堝墠绔�"鐢熸垚閫変腑"澶氶�夋椂鐢級 */
+ public byte[] exportSelectedSeries(String period, String mode, List<String> types) throws Exception {
+ java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
+ try (java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(bos)) {
+ if (types != null) {
+ for (String t : types) {
+ if (t == null || t.trim().isEmpty()) continue;
+ byte[] data = selectedReportData(period, mode, t);
+ if (data != null) {
+ String name = REPORT_FILE_NAMES.get(t);
+ if (name == null) name = "鐢熸垚_" + t + ".xlsx";
+ addZipEntry(zos, name, data);
+ }
+ }
+ }
+ }
+ return bos.toByteArray();
+ }
+
+ private byte[] selectedReportData(String period, String mode, String type) throws Exception {
+ switch (type) {
+ case "cityDetail": return exportCityDetail(period, mode);
+ case "freightRank": return exportFreightRank(period, mode);
+ case "turnoverRank": return exportTurnoverRank(period, mode);
+ case "passengerCityDetail": return exportPassengerCityDetail(period, mode);
+ case "passengerMidDetail": return exportPassengerMidDetail(period, mode);
+ case "passengerMidRank": return exportPassengerMidRank(period, mode);
+ case "passengerMidAnalysis": return exportPassengerMidAnalysis(period, mode);
+ case "summaryWorkbook": return exportSummaryWorkbook(period, mode);
+ case "energySummary": return exportEnergySummary(period);
+ case "investPlan": return investPlan(period, mode);
+ case "investFiveYearLogistics": return investFiveYearLogistics(period, mode);
+ case "investBillion": return investBillion(period, mode);
+ case "investCounty": return investCounty(period, mode);
+ case "cityBusDetail": return exportCityBusDetail(period, mode);
+ case "cityTaxiDetail": return exportCityTaxiDetail(period, mode);
+ case "cityRailFerryDetail": return exportCityRailFerryDetail(period, mode);
+ case "cityPassengerCitySum": return exportCityPassengerCitySum("鐢熸垚_鍩庡競瀹㈣繍瀹㈣繍閲忓垎甯傚窞绱.xlsx", period, mode);
+ case "cityPassengerDetailSum": return exportCityPassengerCitySum("鐢熸垚_鍩庡競瀹㈣繍鍚勫競宸炴槑缁嗚〃.xlsx", period, mode);
+ case "cityPassengerSummary": return exportCityPassengerSummary(period, mode);
+ case "wycSplit": return exportWycSplit(period, mode);
+ default: return null;
+ }
+ }
+
+ private static final Map<String, String> REPORT_FILE_NAMES = new HashMap<>();
+ static {
+ REPORT_FILE_NAMES.put("cityDetail", "鐢熸垚_璐ц繍閲忓垎甯傚窞鏄庣粏.xlsx");
+ REPORT_FILE_NAMES.put("freightRank", "鐢熸垚_璐ц繍閲忔帓鍚�.xlsx");
+ REPORT_FILE_NAMES.put("turnoverRank", "鐢熸垚_鍛ㄨ浆閲忔帓鍚�.xlsx");
+ REPORT_FILE_NAMES.put("passengerCityDetail", "鐢熸垚_鍏矾鏃呭鍒嗗競宸炴槑缁�.xlsx");
+ REPORT_FILE_NAMES.put("passengerMidDetail", "鐢熸垚_鍏矾鏃呭涓彛寰勬槑缁�.xlsx");
+ REPORT_FILE_NAMES.put("passengerMidRank", "鐢熸垚_鍏矾鏃呭涓彛寰勬帓鍚�.xlsx");
+ REPORT_FILE_NAMES.put("passengerMidAnalysis", "鐢熸垚_鍏矾鏃呭涓彛寰勫垎鏋�.xlsx");
+ REPORT_FILE_NAMES.put("energySummary", "鐢熸垚_鑳借繍姹囨�昏〃.xlsx");
+ REPORT_FILE_NAMES.put("investPlan", "鐢熸垚_鍏ㄧ渷棰勫畨鎺掕鍒掕繘搴︽儏鍐垫眹鎬�.xls");
+ REPORT_FILE_NAMES.put("investFiveYearLogistics", "鐢熸垚_鍗佷簲浜旇鍒掔墿娴侀」鐩繘灞曟儏鍐�.xls");
+ REPORT_FILE_NAMES.put("investBillion", "鐢熸垚_婀栧寳鐪侊紙瀹㈣揣绔欏満锛変嚎鍏冩姇璧勯」鐩�.xls");
+ REPORT_FILE_NAMES.put("investCounty", "鐢熸垚_缁忔祹寮哄幙浜ら�氱墿娴佸熀纭�璁炬柦鎶曡祫缁熻鎶ヨ〃.xls");
+ REPORT_FILE_NAMES.put("cityBusDetail", "鐢熸垚_鍩庡競鍏氦瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx");
+ REPORT_FILE_NAMES.put("cityTaxiDetail", "鐢熸垚_宸℃父鍑虹瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx");
+ REPORT_FILE_NAMES.put("cityRailFerryDetail", "鐢熸垚_杞ㄩ亾杞浮瀹㈣繍閲忓垎甯傚窞鏄庣粏.xlsx");
+ REPORT_FILE_NAMES.put("cityPassengerCitySum", "鐢熸垚_鍩庡競瀹㈣繍瀹㈣繍閲忓垎甯傚窞绱.xlsx");
+ REPORT_FILE_NAMES.put("cityPassengerDetailSum", "鐢熸垚_鍩庡競瀹㈣繍鍚勫競宸炴槑缁嗚〃.xlsx");
+ REPORT_FILE_NAMES.put("cityPassengerSummary", "鐢熸垚_鍩庡競瀹㈣繍姹囨��.xlsx");
+ REPORT_FILE_NAMES.put("summaryWorkbook", "鐢熸垚_閬撹矾杩愯緭閲忔眹鎬昏〃.xlsx");
+ REPORT_FILE_NAMES.put("wycSplit", "鐢熸垚_缃戠害杞﹀杩愰噺鎷嗗垎琛�.xlsx");
+ }
+
+ private void addZipEntry(java.util.zip.ZipOutputStream zos, String name, byte[] data) throws Exception {
+ zos.putNextEntry(new java.util.zip.ZipEntry(name));
+ zos.write(data);
+ zos.closeEntry();
+ }
+
+ /** 鍩庡競瀹㈣繍妯℃澘濉厖锛氫互鐩綍涓嬫ā鏉夸负搴曠锛屼繚鐣欐爣棰�/琛ㄥご/鍚堝苟/鍏紡/鏍峰紡锛屼粎鏇挎崲鏁版嵁鍖哄競宸炴湀搴﹀�� */
+ public byte[] exportCityByTemplate(String templateFileName, String period, String mode,
+ Map<Integer, Map<String, double[]>> monthCity,
+ Map<Integer, Map<String, double[]>> lastYearMonthCity) throws Exception {
+ int month = monthOf(period, mode);
+ int year = Integer.parseInt(period.split("-")[0]);
+ File template = resolveTemplate(templateFileName);
+ try (InputStream in = new FileInputStream(template);
+ XSSFWorkbook wb = new XSSFWorkbook(in)) {
+ Sheet sheet = wb.getSheetAt(0);
+ dynamicTitle(sheet, year, month); // 鏍囬鎸夋姤琛ㄦ湡鍔ㄦ�佸寲锛堜笉鍐欐骞翠唤/鏈堜唤锛�
+ // 缁撴瀯瀹堝崼锛氭暟鎹尯搴斾负 鍏ㄧ渷+17甯傚窞 脳 4 鎸囨爣 = 72 琛岋紙1-based 绗�5琛岃捣锛�
+ if (sheet.getLastRowNum() < 75) {
+ throw new RuntimeException("鍩庡競瀹㈣繍妯℃澘鏁版嵁鍖鸿鏁颁笉瓒筹紝璇风‘璁ゆā鏉挎湭鏀圭増: " + templateFileName);
+ }
+ List<String> areas = new java.util.ArrayList<>();
+ areas.add("鍏ㄧ渷");
+ areas.addAll(RegionUtil.cityList());
+ // 妯℃澘鏁版嵁鍖猴細1-based 绗�5琛岃捣锛屾瘡鍦板尯4琛岋紙瀹㈣繍閲�/鍛ㄨ浆閲�/鍩庡競鍐呭杩愰噺/鍩庡競鍐呭懆杞噺锛�
+ int rowIdx = 4;
+ for (int a = 0; a < areas.size(); a++) {
+ String area = areas.get(a);
+ for (int k = 0; k < 4; k++) {
+ Row row = sheet.getRow(rowIdx);
+ if (row == null) row = sheet.createRow(rowIdx);
+ if (a > 0) {
+ // 2026骞� 1..N 鏈堬細搴撳唴鏈夊�煎垯濉紙2浣嶅皬鏁帮級锛屾棤鍊兼竻绌烘ā鏉挎牱渚�
+ for (int m = 1; m <= month; m++) {
+ double v = cityVal(monthCity, area, m, k);
+ Cell c = row.getCell(2 + (m - 1) * 2);
+ if (c == null) c = row.createCell(2 + (m - 1) * 2);
+ if (v == 0) c.setBlank(); else c.setCellValue(round(v, 2));
+ }
+ // 2025骞� 1..12 鏈堬細搴撳唴鏈夊幓骞存暟鎹垯濉紝鍚﹀垯娓呯┖妯℃澘鏍蜂緥
+ for (int m = 1; m <= 12; m++) {
+ double v = cityVal(lastYearMonthCity, area, m, k);
+ Cell c = row.getCell(19 + (m - 1) * 2);
+ if (c == null) c = row.createCell(19 + (m - 1) * 2);
+ if (v == 0) c.setBlank(); else c.setCellValue(round(v, 2));
+ }
+ }
+ rowIdx++;
+ }
+ }
+ // 閲嶇畻鍏紡缂撳瓨鍊硷紙鍏ㄧ渷姹傚拰/鍚屾瘮/绱锛屼繚鐣欏叕寮忥紱姹傚�煎紓甯稿拷鐣ワ級
+ try {
+ wb.getCreationHelper().createFormulaEvaluator().evaluateAll();
+ } catch (Exception e) {
+ log.warn("鍩庡競瀹㈣繍妯℃澘鍏紡姹傚�煎け璐�: {}", e.getMessage());
+ }
+ clearFormulaErrorCells(sheet, 4, sheet.getLastRowNum(), 3, 39);
+ fixCityMonthHeaderText(sheet);
+ return toBytes(wb);
+ }
+ }
+
+ /** 娓呯┖姹傚�肩粨鏋滀负閿欒鐨勫叕寮忓崟鍏冩牸锛堟ā鏉胯法绨垮悓姣斿叕寮忔畫鐣� #REF! 鏃剁Щ闄ゅ叕寮忥紝閬垮厤瀵煎嚭鏄剧ず閿欒锛� */
+ private void clearFormulaErrorCells(Sheet sheet, int startRow, int endRow, int startCol, int endCol) {
+ for (int r = startRow; r <= endRow; r++) {
+ Row row = sheet.getRow(r);
+ if (row == null) continue;
+ for (int c = startCol; c <= endCol; c++) {
+ Cell cell = row.getCell(c);
+ if (cell == null || cell.getCellType() != CellType.FORMULA) continue;
+ try {
+ if (cell.getCachedFormulaResultType() == CellType.ERROR) cell.setBlank();
+ } catch (Exception ignore) {
+ // 缂撳瓨绫诲瀷璇诲彇澶辫触鏃跺拷鐣�
+ }
+ }
+ }
+ }
+
+ /** 娓呯┖宸ヤ綔绨垮叏閮ㄥ伐浣滆〃鍐呮眰鍊肩粨鏋滀负閿欒鐨勫叕寮忓崟鍏冩牸锛堣法绨�/璺ㄨ〃 #REF!銆佺己鍘诲勾鏁版嵁 #DIV/0! 绛夛級 */
+ private void clearFormulaErrorsAll(XSSFWorkbook wb) {
+ for (int i = 0; i < wb.getNumberOfSheets(); i++) {
+ Sheet s = wb.getSheetAt(i);
+ clearFormulaErrorCells(s, 2, s.getLastRowNum(), 1, 60);
+ }
+ }
+
+ /** 鍩庡競瀹㈣繍绫绘ā鏉胯〃澶存湀浠藉垪鑻ヤ负鏈牸寮忓寲鏃ユ湡搴忓垪鍙凤紙濡� 46082锛夛紝鏀瑰啓涓恒�孻YYY骞碝鏈堛�嶆枃鏈� */
+ private void fixCityMonthHeaderText(Sheet sheet) {
+ for (int r = 0; r <= Math.min(sheet.getLastRowNum(), 20); r++) {
+ Row row = sheet.getRow(r);
+ if (row == null) continue;
+ Cell nameCell = row.getCell(0);
+ String nameText = nameCell == null ? null : cellText(nameCell);
+ if (nameText == null || !nameText.contains("鍦板尯")) continue;
+ for (int c = 2; c <= 40; c += 2) {
+ Cell cell = row.getCell(c);
+ if (cell == null || cell.getCellType() != CellType.NUMERIC) continue;
+ double v = cell.getNumericCellValue();
+ if (v < 40000 || v > 60000) continue;
+ java.util.Date d = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
+ cell.setCellValue(new java.text.SimpleDateFormat("yyyy骞碝鏈�").format(d));
+ }
+ }
+ }
+
+ /** 妯℃澘鏂囦欢瀹氫綅锛氶厤缃洰褰� 鈫� user.dir 鈫� user.dir/.. 閫愮骇鍥為�� */
+ private File resolveTemplate(String fileName) throws Exception {
+ return resolveAnyTemplate(templateDir, fileName);
+ }
+
+ /** 鍏矾鏃呭杈撳嚭妯℃澘瀹氫綅锛坉ocs/鍏矾鏃呭+鑳借��/杈撳嚭锛� */
+ private File resolvePassengerTemplate(String fileName) throws Exception {
+ return resolveAnyTemplate(passengerTemplateDir, fileName);
+ }
+
+ /** 閫氱敤妯℃澘鏂囦欢瀹氫綅锛堢敤浜庡煄甯傚杩�/鑳借�楃瓑涓嶅悓妯℃澘鐩綍锛� */
+ private File resolveAnyTemplate(String dir, String fileName) throws Exception {
+ String rel = dir;
+ while (rel.startsWith("./")) rel = rel.substring(2);
+ String[] roots = {
+ dir,
+ System.getProperty("user.dir") + "/" + rel,
+ System.getProperty("user.dir") + "/../" + rel
+ };
+ for (String root : roots) {
+ if (root == null || root.trim().isEmpty()) continue;
+ File f = new File(root, fileName);
+ if (f.exists() && f.isFile()) return f;
+ }
+ throw new RuntimeException("鏈壘鍒版ā鏉挎枃浠�: " + fileName);
+ }
+
+ /** 鍩庡競瀹㈣繍妯℃澘鏍囬鍔ㄦ�佸寲锛氭壂鎻忓叏閮ㄦ枃鏈崟鍏冩牸锛屾浛鎹㈠啓姝荤殑骞翠唤涓庣疮璁″尯闂达紙濡� "2026骞�1-6鏈�" 鈫� "2027骞�1-8鏈�"锛夛紝鍒楁爣棰� "2026骞�1鏈�" 鍙崲骞翠唤锛�"1-12鏈�" 鏁村勾瀵规瘮鍧楋紙2024/2025锛夋爣棰樹繚鎸佸師鏍� */
+ private void dynamicTitle(Sheet sheet, int year, int month) {
+ java.util.regex.Pattern yearP = java.util.regex.Pattern.compile("\\d{4}骞�");
+ java.util.regex.Pattern rangeP = java.util.regex.Pattern.compile("(\\d+)-(\\d+)鏈�");
+ String cum = cumRange(month);
+ for (int r = 0; r <= sheet.getLastRowNum(); r++) {
+ Row row = sheet.getRow(r);
+ if (row == null) continue;
+ for (Cell cell : row) {
+ if (cell.getCellType() != CellType.STRING) continue;
+ String v = cell.getStringCellValue();
+ if (v == null || v.isEmpty() || v.contains("1-12鏈�")) continue; // 鏁村勾瀵规瘮鍧楁爣棰樹繚鎸佸師鏍�
+ String nv = yearP.matcher(v).replaceAll(year + "骞�");
+ nv = rangeP.matcher(nv).replaceAll(java.util.regex.Matcher.quoteReplacement(cum));
+ if (!nv.equals(v)) cell.setCellValue(nv);
+ }
+ }
+ }
+
+ /** 鍩庡競瀹㈣繍鍒嗗競宸炲彇鍊硷紙鏈� 鈫� 甯傚窞 鈫� 鎸囨爣鏁扮粍锛� */
+ private double cityVal(Map<Integer, Map<String, double[]>> monthCity, String area, int m, int idx) {
+ Map<String, double[]> cityMap = monthCity.get(m);
+ if (cityMap == null) return 0;
+ double[] arr = cityMap.get(area);
+ if (arr == null) return 0;
+ return idx < arr.length ? arr[idx] : 0;
+ }
+
+ // ==================== 鎶曡祫妯″潡 4 寮犻瀵兼姤琛紙妯℃澘搴曠鐢熸垚锛岃緭鍑� .xls锛� ====================
+
+ /** 鍔犺浇鎶曡祫 .xls 妯℃澘锛圚SSFWorkbook锛屼繚鐣欏垪瀹�/琛ㄥご/鏍峰紡/鍚堝苟锛� */
+ private HSSFWorkbook loadInvestTemplate(String fileName) throws Exception {
+ File f = resolveAnyTemplate(investTemplateDir, fileName);
+ try (InputStream in = new FileInputStream(f)) {
+ return new HSSFWorkbook(in);
+ }
+ }
+
+ /** 妯℃澘鍗曞厓鏍煎啓鏂囨湰锛氬厛娓呯┖锛堜繚鐣欐牱寮�/鍚堝苟锛夊啀鍐欙紝null/绌虹櫧鐣欑┖ */
+ private void hssfText(Row row, int idx, String v) {
+ Cell c = row.getCell(idx);
+ if (c == null) c = row.createCell(idx);
+ c.setBlank();
+ if (v != null && !v.trim().isEmpty()) c.setCellValue(v.trim());
+ }
+
+ /** 妯℃澘鍗曞厓鏍煎啓鏁板�硷細鍏堟竻绌猴紙淇濈暀鏍峰紡/鍚堝苟锛夊啀鍐� */
+ private void hssfNum(Row row, int idx, Double v) {
+ Cell c = row.getCell(idx);
+ if (c == null) c = row.createCell(idx);
+ c.setBlank();
+ if (v != null) c.setCellValue(v);
+ }
+
+ /** 鍒犻櫎鏁版嵁鍖哄浣欒锛坒romRow..lastKeepRow-1锛夛細鍏堢Щ闄ゅ悎骞跺崟鍏冩牸鍐嶅垹琛岃褰曪紱琛ㄥご鍚堝苟涓嶅彈褰卞搷 */
+ private void trimHssfTail(HSSFSheet sheet, int fromRow, int lastKeepRow) {
+ for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--) {
+ CellRangeAddress m = sheet.getMergedRegion(i);
+ if (m.getFirstRow() >= fromRow && m.getFirstRow() < lastKeepRow) {
+ sheet.removeMergedRegion(i);
+ }
+ }
+ for (int r = lastKeepRow - 1; r >= fromRow; r--) {
+ HSSFRow row = sheet.getRow(r);
+ if (row != null) sheet.removeRow(row);
+ }
+ }
+
+ private void trimHssfTail(HSSFSheet sheet, int fromRow) {
+ trimHssfTail(sheet, fromRow, sheet.getLastRowNum() + 1);
+ }
+
+ /** 鏂板缓琛屽苟澶嶅埗妯℃澘琛屾牱寮忥紙鍚楂橈級锛屼繚璇佷笌妯℃澘鏁版嵁鍖哄瑙備竴鑷� */
+ private HSSFRow createRowLike(HSSFSheet sheet, int rowIdx, HSSFRow styleRow) {
+ HSSFRow row = sheet.createRow(rowIdx);
+ if (styleRow != null) {
+ row.setHeight(styleRow.getHeight());
+ for (int c = 0; c < styleRow.getLastCellNum(); c++) {
+ HSSFCell sc = styleRow.getCell(c);
+ if (sc == null) continue;
+ row.createCell(c).setCellStyle(sc.getCellStyle());
+ }
+ }
+ return row;
+ }
+
+ /** 娣诲姞鍗曡鍚堝苟鍗曞厓鏍硷紙涓庢ā鏉挎暟鎹尯鍚堝苟瑙勫垯涓�鑷达級 */
+ private void addMerge(HSSFSheet sheet, int r, int firstCol, int lastCol) {
+ sheet.addMergedRegion(new CellRangeAddress(r, r, firstCol, lastCol));
+ }
+
+ /** 瑙f瀽 4 浣嶅勾浠戒负鏁板�硷紙鍐欐ā鏉垮勾浠藉垪锛夛紝鏃犳硶瑙f瀽杩斿洖 null */
+ private Double parseYearNum(String t) {
+ if (t == null || t.trim().isEmpty()) return null;
+ String s = t.trim().substring(0, Math.min(4, t.trim().length()));
+ try {
+ return Double.parseDouble(s);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ /** 瑙f瀽 6 浣� YYYYMM 涓烘暟鍊硷紙鍐欐ā鏉垮紑宸ユ椂闂村垪锛� */
+ private Double parseTimeYMNum(String t) {
+ if (t == null || t.trim().isEmpty()) return null;
+ String x = padTimeYM(t.trim()).replaceAll("[^0-9]", "");
+ if (x.length() < 6) return null;
+ try {
+ return Double.parseDouble(x.substring(0, 6));
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ private byte[] toBytesHssf(HSSFWorkbook wb) throws Exception {
+ applyTwoDecimalFormat(wb);
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
wb.write(out);
wb.close();
return out.toByteArray();
}
}
-}
\ No newline at end of file
+
+ /** 鎶曡祫妯℃澘 甯傚窞灏忚妭缁撴瀯锛堣〃1/琛�2 鍔ㄦ�佹彃琛岀敤锛� */
+ private static class InvestSection {
+ String blockCategory;
+ String city;
+ int startRow;
+ int styleRowIdx = -1; // 璇ュ皬鑺傞涓」鐩锛堝鍒舵牱寮忕敤锛�
+ List<Integer> projectRows = new ArrayList<>();
+ Set<Long> matched = new HashSet<>();
+ }
+
+ /** 鍦� pos 琛屼箣鍚庢彃鍏� n 琛岋細涓嬫柟琛屼笅绉伙紙鍚堝苟鍖哄厛鎽橀櫎鍐嶆寜鏂拌鍙锋仮澶嶏級锛屾柊琛屽鍒� styleRow 鏍峰紡/琛岄珮/鍗曡鍚堝苟锛涜繑鍥為涓柊琛岀储寮� */
+ private int insertRowsDown(HSSFSheet sheet, int pos, int n, HSSFRow styleRow) {
+ if (n <= 0) return -1;
+ List<CellRangeAddress> below = new ArrayList<>();
+ for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--) {
+ CellRangeAddress m = sheet.getMergedRegion(i);
+ if (m.getFirstRow() > pos) {
+ below.add(m);
+ sheet.removeMergedRegion(i);
+ }
+ }
+ int last = sheet.getLastRowNum();
+ if (pos < last) {
+ sheet.shiftRows(pos + 1, last, n, true, false);
+ }
+ for (CellRangeAddress m : below) {
+ sheet.addMergedRegion(new CellRangeAddress(m.getFirstRow() + n, m.getLastRow() + n, m.getFirstColumn(), m.getLastColumn()));
+ }
+ int first = pos + 1;
+ for (int i = 0; i < n; i++) {
+ HSSFRow row = createRowLike(sheet, first + i, styleRow);
+ if (styleRow != null) copyRowMerges(sheet, styleRow.getRowNum(), first + i);
+ }
+ return first;
+ }
+
+ /** 澶嶅埗 styleRow 鎵�鍦ㄨ鐨勫崟琛屽悎骞跺尯鍒� toRow锛堟彃鍏ヨ澶栬涓庢ā鏉胯涓�鑷达級 */
+ private void copyRowMerges(HSSFSheet sheet, int fromRow, int toRow) {
+ for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
+ CellRangeAddress m = sheet.getMergedRegion(i);
+ if (m.getFirstRow() == fromRow && m.getLastRow() == fromRow) {
+ sheet.addMergedRegion(new CellRangeAddress(toRow, toRow, m.getFirstColumn(), m.getLastColumn()));
+ }
+ }
+ }
+
+ /** 鎶曡祫琛� 搴忓彿閲嶆帓锛氳〃1 鎸夊潡閲嶇疆銆佽〃2 鎸夊競宸炲皬鑺傞噸缃�佽〃4 鍏ㄨ〃杩炵画锛堟ā鏉�/鎻掑叆琛岀粺涓�鎺掑簭锛� */
+ private void renumberInvestSeq(HSSFSheet sheet, String kind) {
+ int seq = 0;
+ int lastRow = sheet.getLastRowNum();
+ for (int r = 4; r <= lastRow; r++) {
+ HSSFRow row = sheet.getRow(r);
+ if (row == null) continue;
+ String a = nvl(cellText(row.getCell(0)));
+ if ("investPlan".equals(kind)) {
+ if ("涓�銆佸杩愮珯鍦哄熀纭�璁炬柦寤鸿".equals(a) || "浜屻�佷氦閫氱墿娴佸熀纭�璁炬柦寤鸿".equals(a) || "涓夈�佽�佹棫钀ヨ繍璐ц溅鎶ュ簾鏇存柊".equals(a)) {
+ seq = 0;
+ continue;
+ }
+ } else if ("investFiveYear".equals(kind)) {
+ if (isCityLabel(a)) {
+ seq = 0;
+ continue;
+ }
+ }
+ String b = nvl(cellText(row.getCell(1)));
+ if (b.isEmpty()) continue;
+ hssfNum(row, 0, (double) (++seq));
+ }
+ }
+
+ /** 琛�1 椤圭洰琛屽~鍏咃紙妯℃澘琛�/鎻掑叆琛屽叡鐢紱cityText 涓庢ā鏉� B 鍒楁牸寮忎竴鑷达級 */
+ private void fillInvestPlanProjectRow(HSSFRow row, InvestmentProject p, InvestmentMonthly m, int seq, String cityText, String displayName) {
+ hssfNum(row, 0, (double) seq);
+ hssfText(row, 1, cityText);
+ hssfText(row, 2, valueOf(p.getCounty()));
+ hssfText(row, 3, displayName != null && !displayName.trim().isEmpty() ? displayName.trim() : p.getProjectName());
+ hssfText(row, 4, valueOf(p.getConstructNature()));
+ hssfNum(row, 5, parseYearNum(p.getStartTime()));
+ hssfNum(row, 6, parseYearNum(p.getEndTime()));
+ hssfNum(row, 7, p.getTotalInvestment());
+ hssfText(row, 20, p.getApprovalGk());
+ hssfText(row, 21, p.getApprovalCs());
+ if (m != null) {
+ hssfNum(row, 8, m.getStartCum());
+ hssfNum(row, 9, m.getYearPlan());
+ hssfText(row, 13, m.getProgressDesc());
+ hssfNum(row, 22, m.getYearCum());
+ hssfText(row, 23, valueOf(m.getProgressStage()));
+ }
+ }
+
+ /** 琛�2 椤圭洰琛屽~鍏咃紙妯℃澘琛�/鎻掑叆琛屽叡鐢級 */
+ private void fillFiveYearProjectRow(HSSFRow row, InvestmentProject p, InvestmentMonthly m, int seq) {
+ hssfNum(row, 0, (double) seq);
+ hssfText(row, 1, p.getProjectName());
+ hssfText(row, 2, valueOf(p.getBuilderName()));
+ hssfNum(row, 3, parseYearNum(p.getStartTime()));
+ hssfNum(row, 4, parseYearNum(p.getEndTime()));
+ hssfNum(row, 5, p.getTotalInvestment());
+ if (m != null) {
+ hssfNum(row, 6, m.getStartCum());
+ hssfNum(row, 7, m.getYearCum());
+ hssfText(row, 8, valueOf(m.getProgressStage()));
+ hssfText(row, 9, m.getProgressDesc());
+ }
+ }
+
+ /** 琛�4 椤圭洰琛屽~鍏咃紙妯℃澘琛�/鎻掑叆琛屽叡鐢級 */
+ private void fillCountyProjectRow(HSSFRow row, InvestmentProject p, InvestmentMonthly m, int seq) {
+ hssfNum(row, 0, (double) seq);
+ hssfText(row, 1, p.getProjectName());
+ hssfText(row, 2, valueOf(p.getBuilderName()));
+ hssfNum(row, 3, p.getTotalInvestment());
+ if (m != null) {
+ hssfNum(row, 4, m.getStartCum());
+ hssfNum(row, 5, m.getYearPlan());
+ hssfNum(row, 6, m.getYearCum());
+ hssfNum(row, 7, m.getMonthDone());
+ hssfText(row, 8, valueOf(m.getProgressStage()));
+ hssfText(row, 9, m.getProgressDesc());
+ if (m.getBuildingArea() != null && m.getBuildingArea() > 0) hssfNum(row, 12, m.getBuildingArea());
+ }
+ hssfText(row, 15, p.getApprovalGk());
+ hssfText(row, 16, p.getApprovalCs());
+ }
+
+ /** 琛�1锛�2026骞村叏鐪侀瀹夋帓璁″垝杩涘害鎯呭喌姹囨�伙紙妯℃澘搴曠鍘熶綅鏇挎崲锛氫繚鐣欏叏閮ㄨ/鍚堝苟/鍒楀锛屼粎鏇挎崲鏁版嵁锛汥B 椤圭洰澶氫簬妯℃澘棰勭暀琛屾椂鍔ㄦ�佹彃琛岋級 */
+ public byte[] investPlan(String period, String mode) throws Exception {
+ int year = Integer.parseInt(period.split("-")[0]);
+ int month = monthOf(period, mode);
+ List<InvestmentMonthly> monthlies = investMonthlyMapper.selectList(
+ new LambdaQueryWrapper<InvestmentMonthly>()
+ .eq(InvestmentMonthly::getReportPeriod, period));
+ Map<Long, InvestmentProject> pmap = new HashMap<>();
+ List<InvestmentProject> projects = investProjectMapper.selectList(null);
+ for (InvestmentProject p : projects) pmap.put(p.getId(), p);
+ Map<Long, InvestmentMonthly> mByProject = new HashMap<>();
+ for (InvestmentMonthly m : monthlies) mByProject.put(m.getProjectId(), m);
+
+ HSSFWorkbook wb = loadInvestTemplate("妯℃澘_鍏ㄧ渷棰勫畨鎺掕鍒掕繘搴︽儏鍐垫眹鎬�.xls");
+ HSSFSheet sheet = wb.getSheetAt(0);
+ // 鏍囬/琛ㄥご骞翠唤涓庣疮璁℃湀浠�
+ hssfText(sheet.getRow(1), 0, year + "骞村叏鐪佸璐ц繍绔欏満寤鸿棰勫畨鎺掕鍒掕〃");
+ hssfText(sheet.getRow(2), 0, "钃濊壊椤圭洰涓�" + year + "骞村競宸炴嫙鐢虫姤璧勯噾椤圭洰 鍗曚綅锛氫竾鍏�");
+ hssfText(sheet.getRow(3), 22, cumRange(month) + "绱瀹屾垚鎶曡祫");
+ // 缁撴瀯鎵弿锛氬潡(瀹㈣繍/鐗╂祦/鑰佹棫) -> 甯傚窞灏忚妭 -> 椤圭洰琛�
+ List<InvestSection> sections = new ArrayList<>();
+ String blockCategory = null;
+ InvestSection cur = null;
+ int firstProjectRow = -1;
+ int lastRow = sheet.getLastRowNum();
+ for (int r = 5; r <= lastRow; r++) {
+ HSSFRow row = sheet.getRow(r);
+ if (row == null) continue;
+ String a = nvl(cellText(row.getCell(0)));
+ String b = nvl(cellText(row.getCell(1)));
+ String d = nvl(cellText(row.getCell(3)));
+ if (r == 5) continue; // 鍏ㄧ渷鍚堣琛屽崟鐙鐞�
+ if ("涓�銆佸杩愮珯鍦哄熀纭�璁炬柦寤鸿".equals(a) || "浜屻�佷氦閫氱墿娴佸熀纭�璁炬柦寤鸿".equals(a) || "涓夈�佽�佹棫钀ヨ繍璐ц溅鎶ュ簾鏇存柊".equals(a)) {
+ blockCategory = a.startsWith("涓�銆�") ? "瀹㈣繍绔欏満" : (a.startsWith("浜屻��") ? "鐗╂祦鍥尯" : null);
+ cur = null;
+ continue;
+ }
+ if (a.startsWith("涓�銆�") || a.startsWith("浜屻��")) continue; // 棰勫畨鎺掕鍒掑唴/澶� 鍒嗙粍鏍囬锛氬綊褰撳墠灏忚妭
+ if (b.isEmpty() && d.isEmpty()) {
+ cur = new InvestSection();
+ cur.blockCategory = blockCategory;
+ cur.city = templateCityFull(a);
+ cur.startRow = r;
+ sections.add(cur);
+ continue;
+ }
+ if (cur != null) {
+ cur.projectRows.add(r);
+ if (cur.styleRowIdx < 0) cur.styleRowIdx = r;
+ if (firstProjectRow < 0) firstProjectRow = r;
+ }
+ }
+ HSSFRow globalStyle = firstProjectRow >= 0 ? sheet.getRow(firstProjectRow) : null;
+ // 鍘熶綅閫愯鏇挎崲锛氬悎璁�/鍧楁爣棰�/甯傚窞灏忚妭/鍒嗙粍/椤圭洰琛岋紱鏈尮閰嶇殑妯℃澘琛屾竻绌烘牱渚嬫暟鎹紙缁撴瀯/鍚堝苟/鍒楀涓嶅彉锛�
+ int seq = 0;
+ int si = -1;
+ java.util.Set<Long> usedProjectIds = new HashSet<>();
+ for (int r = 5; r <= lastRow; r++) {
+ HSSFRow row = sheet.getRow(r);
+ if (row == null) continue;
+ String a = nvl(cellText(row.getCell(0)));
+ String b = nvl(cellText(row.getCell(1)));
+ String d = nvl(cellText(row.getCell(3)));
+ if (si + 1 < sections.size() && r >= sections.get(si + 1).startRow) si++;
+ InvestSection sec = si >= 0 && si < sections.size() ? sections.get(si) : null;
+ if (r == 5) { // 鍏ㄧ渷鍚堣琛�
+ blankInvestRow(row, 25);
+ hssfText(row, 0, "鍚堣");
+ InvestAgg prov = new InvestAgg();
+ for (InvestmentMonthly m : monthlies) prov.add(m, pmap.get(m.getProjectId()));
+ writeInvestAggHssf(row, prov);
+ continue;
+ }
+ if ("涓�銆佸杩愮珯鍦哄熀纭�璁炬柦寤鸿".equals(a) || "浜屻�佷氦閫氱墿娴佸熀纭�璁炬柦寤鸿".equals(a)) {
+ blockCategory = a.startsWith("涓�銆�") ? "瀹㈣繍绔欏満" : "鐗╂祦鍥尯";
+ blankInvestRow(row, 25);
+ hssfText(row, 0, a);
+ InvestAgg agg = new InvestAgg();
+ for (InvestmentMonthly m : monthlies) {
+ InvestmentProject p = pmap.get(m.getProjectId());
+ if (p != null && blockCategory.equals(p.getCategory())) agg.add(m, p);
+ }
+ writeInvestAggHssf(row, agg);
+ seq = 0;
+ continue;
+ }
+ if ("涓夈�佽�佹棫钀ヨ繍璐ц溅鎶ュ簾鏇存柊".equals(a)) {
+ blockCategory = null; // 鏆傛棤鏁版嵁婧愶細鏁村潡娓呯┖
+ blankInvestRow(row, 25);
+ hssfText(row, 0, a);
+ seq = 0;
+ continue;
+ }
+ if (a.startsWith("涓�銆�") || a.startsWith("浜屻��")) {
+ // 棰勫畨鎺掕鍒掑唴/澶� 鍒嗙粍鏍囬琛岋細鏃犳暟鎹紝浠呬繚鐣欐爣绛�
+ blankInvestRow(row, 25);
+ hssfText(row, 0, a);
+ continue;
+ }
+ if (b.isEmpty() && d.isEmpty()) {
+ // 甯傚窞灏忚妭琛岋細閲嶇畻璇ュ競宸烇紙褰撳墠鍧楃被鍒級鍚堣
+ String city = templateCityFull(a);
+ blankInvestRow(row, 25);
+ hssfText(row, 0, a);
+ InvestAgg agg = new InvestAgg();
+ for (InvestmentMonthly m : monthlies) {
+ InvestmentProject p = pmap.get(m.getProjectId());
+ if (p != null && city.equals(p.getCity())
+ && (blockCategory == null || blockCategory.equals(p.getCategory()))) agg.add(m, p);
+ }
+ writeInvestAggHssf(row, agg);
+ continue;
+ }
+ // 椤圭洰琛岋細鎸� 妯℃澘鍚嶇О+甯傚窞+鍧楃被鍒� 鍖归厤 DB 椤圭洰锛屾湭鍖归厤鏁磋娓呯┖
+ blankInvestRow(row, 25);
+ if (blockCategory == null) continue; // 鑰佹棫璐ц溅娈垫棤鏁版嵁婧�
+ InvestmentProject p = matchInvest(projects, d, b, blockCategory, usedProjectIds);
+ if (p == null) continue;
+ usedProjectIds.add(p.getId());
+ if (sec != null) sec.matched.add(p.getId());
+ InvestmentMonthly m = mByProject.get(p.getId());
+ fillInvestPlanProjectRow(row, p, m, ++seq, b, d);
+ }
+ // 鍔ㄦ�佹彃琛岋細DB 椤圭洰鏁� > 妯℃澘棰勭暀琛屾暟鏃讹紝鍦ㄥ競宸炲皬鑺傛湯灏捐ˉ榻愶紙鑷簳鍚戜笂鎻掕锛岄伩鍏嶈鍙烽敊浣嶏級
+ for (int i = sections.size() - 1; i >= 0; i--) {
+ InvestSection s = sections.get(i);
+ if (s.blockCategory == null || s.city == null) continue; // 鑰佹棫璐ц溅娈垫棤鏁版嵁婧�
+ List<InvestmentProject> extra = new ArrayList<>();
+ for (InvestmentProject p : projects) {
+ if (s.blockCategory.equals(p.getCategory())
+ && s.city.equals(RegionUtil.normalizeCityName(p.getCity()))
+ && !s.matched.contains(p.getId())) extra.add(p);
+ }
+ if (extra.isEmpty()) continue;
+ HSSFRow styleRow = s.styleRowIdx >= 0 ? sheet.getRow(s.styleRowIdx) : globalStyle;
+ int pos = s.projectRows.isEmpty() ? s.startRow : s.projectRows.get(s.projectRows.size() - 1);
+ int first = insertRowsDown(sheet, pos, extra.size(), styleRow);
+ for (int j = 0; j < extra.size(); j++) {
+ HSSFRow row = sheet.getRow(first + j);
+ if (row == null) continue;
+ InvestmentProject p = extra.get(j);
+ fillInvestPlanProjectRow(row, p, mByProject.get(p.getId()), 0, p.getCity(), p.getProjectName());
+ }
+ }
+ renumberInvestSeq(sheet, "investPlan");
+ return toBytesHssf(wb);
+ }
+
+ /** 甯傚窞灏忚妭/鍚堣琛屾暟鍊硷細7鎬绘姇璧� 8鑷紑濮嬬疮璁� 9鏈勾璁″垝 22鑷勾鍒濈疮璁� 23瀹為檯杩涘害锛堥儴/鐪佽祫閲戜笌鑷鏃犳暟鎹簮锛岀暀绌猴級 */
+ private void writeInvestAggHssf(HSSFRow row, InvestAgg agg) {
+ hssfNum(row, 7, agg.total == 0 ? null : agg.total);
+ hssfNum(row, 8, agg.startCum == 0 ? null : agg.startCum);
+ hssfNum(row, 9, agg.yearPlan == 0 ? null : agg.yearPlan);
+ hssfNum(row, 22, agg.yearCum == 0 ? null : agg.yearCum);
+ if (agg.yearPlan > 0) hssfNum(row, 23, round(agg.yearCum / agg.yearPlan, 4));
+ }
+
+
+ private static class InvestAgg {
+ double total, startCum, yearPlan, yearCum;
+
+ void add(InvestmentMonthly m, InvestmentProject p) {
+ if (p != null) total += nz(p.getTotalInvestment());
+ startCum += nz(m.getStartCum());
+ yearPlan += nz(m.getYearPlan());
+ yearCum += nz(m.getYearCum());
+ }
+
+ private double nz(Double v) {
+ return v == null ? 0.0 : v;
+ }
+ }
+
+ /** 琛�2锛�"鍗佷簲浜�"瑙勫垝鐗╂祦椤圭洰杩涘睍鎯呭喌锛堟ā鏉垮簳绋垮師浣嶆浛鎹細淇濈暀鍏ㄩ儴琛�/鍚堝苟/鍒楀锛屼粎鏇挎崲鏁版嵁锛汥B 椤圭洰澶氫簬妯℃澘棰勭暀琛屾椂鍔ㄦ�佹彃琛岋級 */
+ public byte[] investFiveYearLogistics(String period, String mode) throws Exception {
+ List<InvestmentMonthly> monthlies = investMonthlyMapper.selectList(
+ new LambdaQueryWrapper<InvestmentMonthly>()
+ .eq(InvestmentMonthly::getReportPeriod, period));
+ Map<Long, InvestmentProject> pmap = new HashMap<>();
+ List<InvestmentProject> fiveProjects = new java.util.ArrayList<>();
+ for (InvestmentProject p : investProjectMapper.selectList(null)) {
+ pmap.put(p.getId(), p);
+ if (Integer.valueOf(1).equals(p.getIsFiveYear())) fiveProjects.add(p);
+ }
+ Map<Long, InvestmentMonthly> mByProject = new HashMap<>();
+ for (InvestmentMonthly m : monthlies) mByProject.put(m.getProjectId(), m);
+ List<InvestmentMonthly> mine = new java.util.ArrayList<>();
+ for (InvestmentMonthly m : monthlies) {
+ InvestmentProject p = pmap.get(m.getProjectId());
+ if (p != null && Integer.valueOf(1).equals(p.getIsFiveYear())) mine.add(m);
+ }
+
+ HSSFWorkbook wb = loadInvestTemplate("妯℃澘_鍗佷簲浜旇鍒掔墿娴侀」鐩繘灞曟儏鍐�.xls");
+ HSSFSheet sheet = wb.getSheetAt(1); // 銆� 鍒嗛」鐩姇璧勫畬鎴愭儏鍐点��
+ int lastRow = sheet.getLastRowNum();
+ // 缁撴瀯鎵弿锛氬競宸炲皬鑺� -> 椤圭洰琛�
+ List<InvestSection> sections = new ArrayList<>();
+ InvestSection cur = null;
+ int firstProjectRow = -1;
+ for (int r = 4; r <= lastRow; r++) {
+ HSSFRow row = sheet.getRow(r);
+ if (row == null) continue;
+ String a = nvl(cellText(row.getCell(0)));
+ String b = nvl(cellText(row.getCell(1)));
+ if (r == 4) continue; // 鍏ㄧ渷鍚堣琛屽崟鐙鐞�
+ if (b.isEmpty() && isCityLabel(a)) {
+ cur = new InvestSection();
+ cur.city = templateCityFull(a);
+ cur.startRow = r;
+ sections.add(cur);
+ continue;
+ }
+ if (cur != null) {
+ cur.projectRows.add(r);
+ if (cur.styleRowIdx < 0) cur.styleRowIdx = r;
+ if (firstProjectRow < 0) firstProjectRow = r;
+ }
+ }
+ HSSFRow globalStyle = firstProjectRow >= 0 ? sheet.getRow(firstProjectRow) : null;
+ String currentCity = null;
+ int seq = 0;
+ int si = -1;
+ for (int r = 4; r <= lastRow; r++) {
+ HSSFRow row = sheet.getRow(r);
+ if (row == null) continue;
+ String a = nvl(cellText(row.getCell(0)));
+ String b = nvl(cellText(row.getCell(1)));
+ if (si + 1 < sections.size() && r >= sections.get(si + 1).startRow) si++;
+ InvestSection sec = si >= 0 && si < sections.size() ? sections.get(si) : null;
+ if (r == 4) { // 鍏ㄧ渷鍚堣琛�
+ blankInvestRow(row, 12);
+ hssfText(row, 0, "鍚堣");
+ InvestAgg total = new InvestAgg();
+ for (InvestmentMonthly m : mine) total.add(m, pmap.get(m.getProjectId()));
+ hssfNum(row, 5, total.total == 0 ? null : total.total);
+ hssfNum(row, 6, total.startCum == 0 ? null : total.startCum);
+ hssfNum(row, 7, total.yearCum == 0 ? null : total.yearCum);
+ continue;
+ }
+ if (b.isEmpty() && isCityLabel(a)) {
+ currentCity = templateCityFull(a);
+ seq = 0;
+ blankInvestRow(row, 12);
+ hssfText(row, 0, a);
+ InvestAgg agg = new InvestAgg();
+ for (InvestmentMonthly m : mine) {
+ InvestmentProject p = pmap.get(m.getProjectId());
+ if (p != null && currentCity.equals(p.getCity())) agg.add(m, p);
+ }
+ hssfNum(row, 5, agg.total == 0 ? null : agg.total);
+ hssfNum(row, 6, agg.startCum == 0 ? null : agg.startCum);
+ hssfNum(row, 7, agg.yearCum == 0 ? null : agg.yearCum);
+ continue;
+ }
+ // 椤圭洰琛岋細鎸� 妯℃澘鍚嶇О+甯傚窞 鍖归厤 DB 鍗佷簲浜旈」鐩紝鏈尮閰嶆暣琛屾竻绌�
+ blankInvestRow(row, 12);
+ InvestmentProject p = matchInvest(fiveProjects, b, currentCity, null);
+ if (p == null) continue;
+ if (sec != null) sec.matched.add(p.getId());
+ InvestmentMonthly m = mByProject.get(p.getId());
+ fillFiveYearProjectRow(row, p, m, ++seq);
+ }
+ // 鍔ㄦ�佹彃琛岋細DB 鍗佷簲浜旈」鐩暟 > 妯℃澘棰勭暀琛屾暟鏃讹紝鍦ㄥ競宸炲皬鑺傛湯灏捐ˉ榻�
+ for (int i = sections.size() - 1; i >= 0; i--) {
+ InvestSection s = sections.get(i);
+ if (s.city == null) continue;
+ List<InvestmentProject> extra = new ArrayList<>();
+ for (InvestmentProject p : fiveProjects) {
+ if (s.city.equals(RegionUtil.normalizeCityName(p.getCity()))
+ && !s.matched.contains(p.getId())) extra.add(p);
+ }
+ if (extra.isEmpty()) continue;
+ HSSFRow styleRow = s.styleRowIdx >= 0 ? sheet.getRow(s.styleRowIdx) : globalStyle;
+ int pos = s.projectRows.isEmpty() ? s.startRow : s.projectRows.get(s.projectRows.size() - 1);
+ int first = insertRowsDown(sheet, pos, extra.size(), styleRow);
+ for (int j = 0; j < extra.size(); j++) {
+ HSSFRow row = sheet.getRow(first + j);
+ if (row == null) continue;
+ InvestmentProject p = extra.get(j);
+ fillFiveYearProjectRow(row, p, mByProject.get(p.getId()), 0);
+ }
+ }
+ renumberInvestSeq(sheet, "investFiveYear");
+ return toBytesHssf(wb);
+ }
+
+ /** 琛�4锛氾紙缁忔祹寮哄幙椤圭洰锛夋箹鍖楃渷浜ら�氱墿娴佸熀纭�璁炬柦鎶曡祫缁熻鎶ヨ〃锛堟ā鏉垮簳绋垮師浣嶆浛鎹細淇濈暀鍏ㄩ儴琛�/鍚堝苟/鍒楀锛屼粎鏇挎崲鏁版嵁锛汥B 椤圭洰澶氫簬妯℃澘棰勭暀琛屾椂鍔ㄦ�佹彃琛岋級 */
+ public byte[] investCounty(String period, String mode) throws Exception {
+ List<InvestmentMonthly> monthlies = investMonthlyMapper.selectList(
+ new LambdaQueryWrapper<InvestmentMonthly>()
+ .eq(InvestmentMonthly::getReportPeriod, period));
+ Map<Long, InvestmentProject> pmap = new HashMap<>();
+ List<InvestmentProject> countyProjects = new java.util.ArrayList<>();
+ for (InvestmentProject p : investProjectMapper.selectList(null)) {
+ pmap.put(p.getId(), p);
+ if (Integer.valueOf(1).equals(p.getIsCounty())) countyProjects.add(p);
+ }
+ Map<Long, InvestmentMonthly> mByProject = new HashMap<>();
+ for (InvestmentMonthly m : monthlies) mByProject.put(m.getProjectId(), m);
+ int year = Integer.parseInt(period.split("-")[0]);
+ int month = monthOf(period, mode);
+
+ HSSFWorkbook wb = loadInvestTemplate("妯℃澘_缁忔祹寮哄幙鎶曡祫缁熻鎶ヨ〃.xls");
+ HSSFSheet sheet = wb.getSheetAt(0);
+ hssfText(sheet.getRow(0), 0, "锛堢粡娴庡己鍘块」鐩級婀栧寳鐪佷氦閫氱墿娴佸熀纭�璁炬柦鎶曡祫缁熻鎶ヨ〃锛�" + month + "鏈堟湀鎶ワ級");
+ hssfText(sheet.getRow(1), 0, "鍏ㄧ渷璐ц繍锛堢墿娴侊級鍩虹璁炬柦寤鸿鎶曡祫鏈堟姤锛�" + year + "骞�" + month + "鏈堬級");
+ int lastRow = Math.min(sheet.getLastRowNum(), 65533);
+ int seq = 0;
+ int lastProjectRow = -1;
+ Set<Long> matched = new HashSet<>();
+ for (int r = 4; r <= lastRow; r++) {
+ HSSFRow row = sheet.getRow(r);
+ if (row == null) continue;
+ String name = nvl(cellText(row.getCell(1)));
+ if (name.isEmpty()) continue; // 妯℃澘灏鹃儴绌鸿涓嶅鐞�
+ lastProjectRow = r;
+ blankInvestRow(row, 20);
+ InvestmentProject p = matchInvest(countyProjects, name, null, null);
+ if (p == null) continue;
+ matched.add(p.getId());
+ InvestmentMonthly m = mByProject.get(p.getId());
+ fillCountyProjectRow(row, p, m, ++seq);
+ }
+ // 鍔ㄦ�佹彃琛岋細DB 缁忔祹寮哄幙椤圭洰鏁� > 妯℃澘棰勭暀琛屾暟鏃讹紝鍦ㄩ」鐩尯鏈熬琛ラ綈
+ List<InvestmentProject> extra = new ArrayList<>();
+ for (InvestmentProject p : countyProjects) {
+ if (!matched.contains(p.getId())) extra.add(p);
+ }
+ if (!extra.isEmpty()) {
+ HSSFRow styleRow = sheet.getRow(4);
+ int pos = lastProjectRow >= 4 ? lastProjectRow : 3;
+ int first = insertRowsDown(sheet, pos, extra.size(), styleRow);
+ for (int j = 0; j < extra.size(); j++) {
+ HSSFRow row = sheet.getRow(first + j);
+ if (row == null) continue;
+ InvestmentProject p = extra.get(j);
+ fillCountyProjectRow(row, p, mByProject.get(p.getId()), 0);
+ }
+ }
+ renumberInvestSeq(sheet, "investCounty");
+ return toBytesHssf(wb);
+ }
+
+
+ /** 琛�3锛氭箹鍖楃渷锛堝璐х珯鍦猴級浜垮厓鎶曡祫椤圭洰锛堟ā鏉垮簳绋� .xls锛屾姇璧勬�昏〃 + 瑙勪笂椤圭洰琛� 涓� sheet锛� */
+ public byte[] investBillion(String period, String mode) throws Exception {
+ List<InvestmentMonthly> monthlies = investMonthlyMapper.selectList(
+ new LambdaQueryWrapper<InvestmentMonthly>()
+ .eq(InvestmentMonthly::getReportPeriod, period));
+ Map<Long, InvestmentProject> pmap = new HashMap<>();
+ for (InvestmentProject p : investProjectMapper.selectList(null)) pmap.put(p.getId(), p);
+ List<InvestmentMonthly> mine = new java.util.ArrayList<>();
+ for (InvestmentMonthly m : monthlies) {
+ InvestmentProject p = pmap.get(m.getProjectId());
+ if (p != null && Integer.valueOf(1).equals(p.getIsBillion())) mine.add(m);
+ }
+ int year = Integer.parseInt(period.split("-")[0]);
+ int month = monthOf(period, mode);
+
+ HSSFWorkbook wb = loadInvestTemplate("妯℃澘_浜垮厓鎶曡祫椤圭洰.xls");
+ // ---- sheet1 鎶曡祫鎬昏〃锛氬浐瀹氶鏋讹紝浠呭~锛堜簲锛夊叾浠� 鍏ㄥ勾棰勮锛堝叏鐪佹湰骞磋鍒掓姌浜匡級 ----
+ HSSFSheet s1 = wb.getSheetAt(0);
+ hssfText(s1.getRow(0), 0, year + "骞村浐瀹氳祫浜ф姇璧勯璁″畬鎴愭儏鍐�");
+ double provinceYearPlan = 0;
+ for (InvestmentMonthly m : monthlies) provinceYearPlan += nz(m.getYearPlan());
+ HSSFRow rowOther = s1.getRow(9);
+ for (int c = 1; c <= 5; c++) hssfNum(rowOther, c, null);
+ hssfNum(rowOther, 5, provinceYearPlan == 0 ? null : round(provinceYearPlan / 10000, 2));
+ // ---- sheet2 瑙勪笂椤圭洰琛細琛ㄥご骞翠唤 + 鍚堣 + 椤圭洰琛� ----
+ HSSFSheet s2 = wb.getSheetAt(1);
+ hssfText(s2.getRow(0), 0, year + "骞翠氦閫氬缓璁鹃」鐩偍澶囨儏鍐碉紙瑙勬ā浠ヤ笂椤圭洰锛�");
+ hssfText(s2.getRow(2), 5, "鎴鍒�" + year + "骞�" + month + "鏈堝簳寤鸿鐘舵��");
+ hssfText(s2.getRow(2), 9, "鎴嚦" + (year - 1) + "骞村勾搴曞疄闄呭畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 10, year + "骞�1-3鏈堝疄闄呭畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 11, year + "骞�4鏈堣鍒掑畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 12, year + "骞寸浜屽搴﹁鍒掑畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 13, year + "骞村叏骞磋鍒掑畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 16, year + "骞�1-4鏈堣鍒掑畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 17, year + "骞�4鏈堝疄闄呭畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 18, year + "骞�1-4鏈堢疮璁″畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 19, year + "骞�5鏈堝疄闄呭畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 21, year + "骞�6鏈堝疄闄呭畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 22, year + "骞寸浜屽搴﹀疄闄呭畬鎴愭姇璧勶紙涓囧厓锛�");
+ hssfText(s2.getRow(2), 23, year + "骞�" + month + "鏈堝疄闄呭畬鎴愭姇璧�");
+ // 鍚堣琛� R4锛坈ol0-1 灞炰簬琛ㄥご鍚堝苟鍖猴紝淇濈暀锛涙竻绌哄苟閲嶅啓鏁版嵁鍒楋級
+ HSSFRow totalRow = s2.getRow(4);
+ for (int c = 2; c <= 23; c++) hssfNum(totalRow, c, null);
+ InvestAgg total = new InvestAgg();
+ for (InvestmentMonthly m : mine) total.add(m, pmap.get(m.getProjectId()));
+ hssfNum(totalRow, 8, total.total == 0 ? null : total.total);
+ hssfNum(totalRow, 13, total.yearPlan == 0 ? null : total.yearPlan);
+ hssfNum(totalRow, 23, sumMonth(mine) == 0 ? null : sumMonth(mine));
+ // 椤圭洰琛岋細淇濈暀妯℃澘 R79 娉ㄩ噴琛�
+ HSSFRow styleProject = s2.getRow(5);
+ trimHssfTail(s2, 5, 79);
+ int rowIdx = 5;
+ for (InvestmentMonthly m : mine) {
+ InvestmentProject p = pmap.get(m.getProjectId());
+ HSSFRow row = createRowLike(s2, rowIdx++, styleProject);
+ hssfText(row, 0, "婀栧寳鐪�");
+ hssfText(row, 1, RegionUtil.shortName(p.getCity()));
+ hssfText(row, 2, p.getProjectName());
+ hssfText(row, 3, "瀹㈣繍绔欏満".equals(p.getCategory()) ? "缁煎悎瀹㈣繍鏋㈢航" : "缁煎悎璐ц繍鏋㈢航");
+ hssfText(row, 5, valueOf(m.getProgressStage()));
+ hssfText(row, 6, valueOf(p.getConstructNature()));
+ hssfNum(row, 7, parseTimeYMNum(p.getStartTime()));
+ hssfNum(row, 8, p.getTotalInvestment());
+ hssfNum(row, 13, m.getYearPlan());
+ hssfNum(row, 23, m.getMonthDone());
+ }
+ trimHssfTail(s2, rowIdx, 79);
+ return toBytesHssf(wb);
+ }
+
+ /** 绌轰覆褰掍竴锛坈ellText 鍙兘杩斿洖 null锛� */
+ private String nvl(String v) {
+ return v == null ? "" : v.trim();
+ }
+
+ /** 娓呯┖妯℃澘鏁版嵁琛屾寚瀹氳寖鍥村崟鍏冩牸锛堜繚鐣欐牱寮忎笌鍚堝苟鍗曞厓鏍硷級 */
+ private void blankInvestRow(HSSFRow row, int lastCol) {
+ if (row == null) return;
+ for (int c = 0; c <= lastCol; c++) {
+ Cell cell = row.getCell(c);
+ if (cell != null) cell.setBlank();
+ }
+ }
+
+ /** 妯℃澘甯傚窞鐭悕 -> 瑙勮寖甯傚窞鍚嶏紙姝︽眽->姝︽眽甯傘�佹灄鍖�->绁炲啘鏋舵灄鍖恒�佹仼鏂藉窞->鎭╂柦宸烇級 */
+ private String templateCityFull(String label) {
+ if (label == null) return null;
+ String t = label.trim();
+ String canon = RegionUtil.normalizeCityName(t);
+ for (String city : RegionUtil.cityList()) {
+ if (city.equals(canon)) return city;
+ }
+ for (String city : RegionUtil.cityList()) {
+ if (RegionUtil.shortName(city).equals(canon) || RegionUtil.shortName(city).equals(t)) return city;
+ }
+ return canon;
+ }
+
+ /** 鍒ゆ柇妯℃澘琛� A 鍒楁槸鍚︿负甯傚窞灏忚妭鏍囩 */
+ private boolean isCityLabel(String label) {
+ if (label == null || label.isEmpty()) return false;
+ String full = templateCityFull(label);
+ return full != null && RegionUtil.cityList().contains(full);
+ }
+
+ /** 鍦ㄥ�欓�夐」鐩睜涓寜鍚嶇О鍖归厤 DB 椤圭洰锛堝彲閫� 甯傚窞/绫诲埆 杩囨护 + 鍘垮尯鍓嶇紑娑堟锛夛紝鏈懡涓繑鍥� null */
+ private InvestmentProject matchInvest(List<InvestmentProject> pool, String name, String cityFull, String category) {
+ return matchInvest(pool, name, cityFull, category, null);
+ }
+
+ /** 甯﹀凡鍗犵敤鎺掗櫎鐨勫尮閰嶏細鍚屼竴 DB 椤圭洰鍙厑璁稿~鍏呬竴琛岋紙閬垮厤妯℃澘涓�鏈�/浜屾湡鍚屽悕琛岄噸澶嶈緭鍑猴級 */
+ private InvestmentProject matchInvest(List<InvestmentProject> pool, String name, String cityFull, String category, Set<Long> excludeIds) {
+ if (name == null || name.trim().isEmpty()) return null;
+ String norm = normInvestName(name);
+ if (norm.isEmpty()) return null;
+ String cityCanon = cityFull == null || cityFull.trim().isEmpty() ? null : RegionUtil.normalizeCityName(cityFull);
+ String county = extractInvestCounty(name);
+ List<InvestmentProject> cands = new java.util.ArrayList<>();
+ for (InvestmentProject p : pool) {
+ if (excludeIds != null && excludeIds.contains(p.getId())) continue;
+ if (category != null && !category.equals(p.getCategory())) continue;
+ if (cityCanon != null && !cityCanon.equals(RegionUtil.normalizeCityName(p.getCity()))) continue;
+ cands.add(p);
+ }
+ if (cands.isEmpty()) return null;
+ // 褰掍竴鍖栧悓鍚嶅鍊欓�夛細鍘垮尯鍓嶇紑娑堟锛堝 缃楃敯鍘跨患鍚堢墿娴佸洯 vs 鍜镐赴鍘跨患鍚堢墿娴佸洯锛�
+ if (!county.isEmpty()) {
+ for (InvestmentProject p : cands) {
+ if (normInvestName(p.getProjectName()).equals(norm)
+ && p.getProjectName() != null && p.getProjectName().contains(county)) {
+ return p;
+ }
+ }
+ }
+ InvestmentProject best = null;
+ int bestScore = Integer.MIN_VALUE;
+ for (InvestmentProject p : cands) {
+ String pn = normInvestName(p.getProjectName());
+ if (pn.isEmpty()) continue;
+ int s = investNameScore(norm, pn, county, p.getProjectName());
+ if (s > bestScore) {
+ bestScore = s;
+ best = p;
+ }
+ }
+ return bestScore > 0 ? best : null;
+ }
+
+ /** 椤圭洰鍚嶅綊涓�鍖栵細鍘绘嫭鍙峰瓧绗︺�佽繛鎺ョ锛岀綏椹暟瀛楃粺涓�锛屽幓鐪�/甯�/鍘�/鍖哄墠缂�涓庣┖鐧斤紙涓庡鏍稿紩鎿庝竴鑷达級 */
+ private String normInvestName(String name) {
+ if (name == null) return "";
+ String s = name.trim();
+ s = s.replaceAll("[锛�(]", "").replaceAll("[锛�)]", "");
+ s = s.replaceAll("[路鈥⑩�旓紞_\\-]", "");
+ s = s.replaceAll("[鈪犫叀鈪⑩叄鈪も叆鈪︹収鈪ㄢ叐鈪扳叡鈪测叧鈪粹叺鈪垛叿鈪糕吂]", "I");
+ s = s.replaceAll("^(婀栧寳鐪亅姝︽眽甯倈榛勭煶甯倈鍗佸牥甯倈瀹滄槍甯倈瑗勯槼甯倈閯傚窞甯倈鑽嗛棬甯倈瀛濇劅甯倈鑽嗗窞甯倈榛勫唸甯倈鍜稿畞甯倈闅忓窞甯倈鎭╂柦宸瀨浠欐甯倈娼滄睙甯倈澶╅棬甯倈绁炲啘鏋舵灄鍖�)", "");
+ s = s.replaceAll("^(?:[\\u4e00-\\u9fa5]{2,4}(?:鍘縷甯倈鍖�))", "");
+ s = s.replaceAll("\\s+", "");
+ return s;
+ }
+
+ /** 鍚嶇О鐩镐技搴﹁瘎鍒嗭細绮剧‘>鍓嶇紑鍖呭惈>涓悗閮ㄥ寘鍚�>5瀛�>瀛愬簭鍒�>鏈�闀垮叕鍏卞瓙涓诧紱鍘垮尯鍓嶇紑涓嶄竴鑷存嫆缁�/澶ф墸鍒� */
+ private int investNameScore(String norm, String key, String county, String rawB) {
+ if (norm.equals(key)) {
+ // 褰掍竴鍖栧悗鍚屽悕锛氳嫢妯℃澘甯﹀幙鍖哄墠缂�鑰屽�欓�夊師濮嬪悕涓嶅惈璇ュ幙鍖� 鈫� 鎷掔粷锛堥槻 瀹滈兘甯� vs 褰撻槼甯� 璇厤锛�
+ if (county != null && !county.isEmpty() && (rawB == null || !rawB.contains(county))) return -1;
+ return 2000;
+ }
+ if (key.length() < 5 || norm.length() < 5) return -1;
+ String shortSide = key.length() <= norm.length() ? key : norm;
+ String longSide = key.length() > norm.length() ? key : norm;
+ int idx = longSide.indexOf(shortSide);
+ int lenDiff = Math.abs(key.length() - norm.length());
+ int base;
+ if (idx == 0) {
+ base = 1000 - lenDiff * 2;
+ } else if (idx > 0 && shortSide.length() >= 6) {
+ base = 500 - idx * 5 - lenDiff * 2 + shortSide.length();
+ } else if (idx > 0 && shortSide.length() == 5 && lenDiff <= 5) {
+ String diff = longSide.substring(0, idx) + longSide.substring(idx + shortSide.length());
+ if (diff.matches(".*(鍘縷甯倈宸�).*")) return -1;
+ base = 400 - idx * 5 - lenDiff;
+ } else if (isInvestSubsequence(shortSide, longSide) && lenDiff <= 8) {
+ base = 300 - lenDiff * 3;
+ } else {
+ int l = investLcs(norm, key);
+ if (l >= 6) {
+ base = 200 + l * 5 - lenDiff;
+ } else if (l == 5 && lenDiff <= 4 && county != null && !county.isEmpty()
+ && rawB != null && rawB.contains(county)) {
+ base = 150 + l * 5 - lenDiff;
+ } else {
+ return -1;
+ }
+ }
+ if (county != null && !county.isEmpty() && (rawB == null || !rawB.contains(county))) {
+ base -= 400;
+ }
+ return base;
+ }
+
+ /** 鍒ゆ柇鐭悕鏄惁涓洪暱鍚嶇殑瀛楃瀛愬簭鍒� */
+ private boolean isInvestSubsequence(String shortSide, String longSide) {
+ int i = 0;
+ for (int j = 0; i < shortSide.length() && j < longSide.length(); j++) {
+ if (shortSide.charAt(i) == longSide.charAt(j)) i++;
+ }
+ return i == shortSide.length();
+ }
+
+ /** 鏈�闀垮叕鍏卞瓙涓查暱搴� */
+ private int investLcs(String a, String b) {
+ int n = a.length(), m = b.length();
+ if (n == 0 || m == 0) return 0;
+ int[][] dp = new int[n + 1][m + 1];
+ int max = 0;
+ for (int i = 1; i <= n; i++) {
+ for (int j = 1; j <= m; j++) {
+ if (a.charAt(i - 1) == b.charAt(j - 1)) {
+ dp[i][j] = dp[i - 1][j - 1] + 1;
+ if (dp[i][j] > max) max = dp[i][j];
+ }
+ }
+ }
+ return max;
+ }
+
+ /** 鎻愬彇鍚嶇О涓殑 鍘�/甯�/鍖� 鍓嶇紑锛堝 鍜镐赴鍘裤�佸疁閮藉競锛� */
+ private String extractInvestCounty(String name) {
+ if (name == null) return "";
+ java.util.regex.Matcher mm = java.util.regex.Pattern.compile("([\\u4e00-\\u9fa5]{2,4}(?:鍘縷甯倈鍖�))").matcher(name);
+ if (mm.find()) return mm.group(1);
+ return "";
+ }
+
+
+ private double sumMonth(List<InvestmentMonthly> list) {
+ double s = 0;
+ for (InvestmentMonthly m : list) s += nz(m.getMonthDone());
+ return s;
+ }
+
+ private String padTimeYM(String t) {
+ if (t == null) return null;
+ String x = t.trim();
+ if (x.matches("\\d{4}")) return x + "01";
+ return x;
+ }
+
+ private String valueOf(String v) {
+ return v == null || v.trim().isEmpty() ? "" : v.trim();
+ }
+ private double nz(Double v) {
+ return v == null ? 0.0 : v;
+ }
+ /** 鐢熸垚琛ㄦ暟鍊煎垪缁熶竴鏍峰紡锛氫繚鐣欏叏绮惧害鏁板�硷紝鏄剧ず涓や綅灏忔暟锛涙暣鏁板�间笌 %/鏃ユ湡/绉戝璁℃暟绛夋棦鏈夋牱寮忎笉鏀瑰彉 */
+ private void applyTwoDecimalFormat(org.apache.poi.ss.usermodel.Workbook wb) {
+ if (wb == null) return;
+ org.apache.poi.ss.usermodel.DataFormat df = wb.createDataFormat();
+ short fmtTwo = df.getFormat("0.00");
+ for (int s = 0; s < wb.getNumberOfSheets(); s++) {
+ org.apache.poi.ss.usermodel.Sheet sh = wb.getSheetAt(s);
+ if (sh == null) continue;
+ for (org.apache.poi.ss.usermodel.Row row : sh) {
+ if (row == null) continue;
+ for (org.apache.poi.ss.usermodel.Cell cell : row) {
+ if (cell == null) continue;
+ try {
+ CellType ct = cell.getCellType();
+ if (ct != CellType.NUMERIC && ct != CellType.FORMULA) continue;
+ if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) continue;
+ boolean integral = false;
+ if (ct == CellType.NUMERIC) {
+ integral = Math.rint(cell.getNumericCellValue()) == cell.getNumericCellValue();
+ } else if (cell.getCachedFormulaResultType() == CellType.NUMERIC) {
+ integral = Math.rint(cell.getNumericCellValue()) == cell.getNumericCellValue();
+ }
+ if (integral) continue; // 鏁存暟涓嶆樉绀� .00锛堝惈鍏紡缁撴灉涓烘暣鏁扮殑鏍硷級
+ org.apache.poi.ss.usermodel.CellStyle cs = cell.getCellStyle();
+ if (cs == null) continue;
+ String f = cs.getDataFormatString();
+ if (f == null) f = "";
+ if (f.contains("%") || f.contains("E") || f.contains("0.00")) continue;
+ boolean plain = f.isEmpty() || "General".equals(f) || "general".equals(f)
+ || "0".equals(f) || "#,##0".equals(f) || "0.0".equals(f) || "#,##0.0".equals(f);
+ if (!plain) continue;
+ org.apache.poi.ss.usermodel.CellStyle ns = wb.createCellStyle();
+ ns.cloneStyleFrom(cs);
+ ns.setDataFormat(fmtTwo);
+ cell.setCellStyle(ns);
+ } catch (Exception ignore) {
+ // 涓埆鍗曞厓鏍兼牸寮忓紓甯镐笉闃诲瀵煎嚭
+ }
+ }
+ }
+ }
+ }
+
+ /** 姹囨�昏〃瀵煎嚭鍚庢寜鍐呭鑷姩鍔犲鍒楀锛堝彧鍔犲涓嶇缉绐勶紱璺宠繃鍚堝苟鍗曞厓鏍兼爣棰橈紝闃查暱鏍囬鎶婂崟鍒楁拺鐖嗭級 */
+ private void autoFitContentColumns(org.apache.poi.ss.usermodel.Workbook wb) {
+ if (wb == null) return;
+ org.apache.poi.ss.usermodel.DataFormatter dfmt = new org.apache.poi.ss.usermodel.DataFormatter();
+ for (int s = 0; s < wb.getNumberOfSheets(); s++) {
+ org.apache.poi.ss.usermodel.Sheet sh = wb.getSheetAt(s);
+ if (sh == null) continue;
+ java.util.Set<String> merged = new java.util.HashSet<>();
+ for (org.apache.poi.ss.util.CellRangeAddress ra : sh.getMergedRegions()) {
+ for (int r = ra.getFirstRow(); r <= ra.getLastRow(); r++) {
+ for (int c = ra.getFirstColumn(); c <= ra.getLastColumn(); c++) {
+ merged.add(r + ":" + c);
+ }
+ }
+ }
+ int maxCol = -1;
+ for (org.apache.poi.ss.usermodel.Row row : sh) {
+ if (row == null) continue;
+ maxCol = Math.max(maxCol, (int) row.getLastCellNum() - 1);
+ }
+ if (maxCol < 0) continue;
+ int[] need = new int[maxCol + 1];
+ for (org.apache.poi.ss.usermodel.Row row : sh) {
+ if (row == null) continue;
+ for (org.apache.poi.ss.usermodel.Cell cell : row) {
+ int c = cell.getColumnIndex();
+ if (c > maxCol || merged.contains(row.getRowNum() + ":" + c)) continue;
+ String txt;
+ try {
+ txt = dfmt.formatCellValue(cell);
+ } catch (Exception ignore) {
+ continue;
+ }
+ if (txt == null || txt.isEmpty()) continue;
+ int units = 0;
+ for (int i = 0; i < txt.length(); i++) {
+ units += isWideChar(txt.charAt(i)) ? 2 : 1;
+ }
+ if (units > need[c]) need[c] = Math.min(units, 34); // 闀挎枃鏈笉鎶婂崟鍒楁拺鐖�
+ }
+ }
+ for (int c = 0; c <= maxCol; c++) {
+ if (need[c] <= 0) continue;
+ int target = Math.min(need[c] + 2, 46) * 256;
+ if (target > sh.getColumnWidth(c)) sh.setColumnWidth(c, target);
+ }
+ }
+ }
+
+ /** CJK / 鍏ㄨ瀛楃鎸変袱鍊嶅搴﹁锛堣繎浼� Excel 鏄剧ず鍒楀锛� */
+ private boolean isWideChar(char ch) {
+ return (ch >= 0x2E80 && ch <= 0x9FFF) || (ch >= 0xF900 && ch <= 0xFAFF)
+ || (ch >= 0xFF00 && ch <= 0xFFEF);
+ }
+
+ private byte[] toBytes(XSSFWorkbook wb) throws Exception {
+ applyTwoDecimalFormat(wb);
+ try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+ wb.write(out);
+ wb.close();
+ return out.toByteArray();
+ }
+ }
+}
--
Gitblit v1.9.1