| | |
| | | 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.Font; |
| | | import org.apache.poi.ss.usermodel.HorizontalAlignment; |
| | | import org.apache.poi.ss.usermodel.IndexedColors; |
| | | import org.apache.poi.ss.usermodel.Row; |
| | | import org.apache.poi.ss.usermodel.Sheet; |
| | | import org.apache.poi.ss.usermodel.VerticalAlignment; |
| | | import org.apache.poi.ss.usermodel.FormulaEvaluator; |
| | | import org.apache.poi.xssf.usermodel.XSSFSheet; |
| | | import org.apache.poi.xssf.usermodel.XSSFWorkbook; |
| | |
| | | rows = addReadyCount(() -> investMonthlyMapper.selectCount(periodQw(period, mode, InvestmentMonthly::getReportPeriod)), "投资市州单表/汇总数据", notes); |
| | | auditTypes.add("INVEST"); |
| | | break; |
| | | case "energySummary": |
| | | case "energyQuarterSummary": |
| | | case "energyLeader": |
| | | rows = addReadyCount(() -> energyMapper.selectCount(periodQw(period, mode, EnergyVehicleQuarterly::getReportPeriod)), "能耗车辆季度数据", notes); |
| | | auditTypes.add("H204"); |
| | | break; |
| | |
| | | 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; |
| | | else if ("energyQuarterSummary".equals(t) || "energyLeader".equals(t)) energy = true; |
| | | } |
| | | |
| | | // 月度覆盖:该年 1..month 中哪些月有源数据 |
| | |
| | | if ("investPassengerDetail".equals(t)) investPreview(period, mode, "客运站场", summary, problems); |
| | | else if ("investLogisticsDetail".equals(t)) investPreview(period, mode, "物流园区", summary, problems); |
| | | else investPreview(period, mode, summary, problems); |
| | | } else if ("energySummary".equals(t)) { |
| | | } else if ("energyQuarterSummary".equals(t) || "energyLeader".equals(t)) { |
| | | Long ec = energyMapper.selectCount(periodQw(period, mode, EnergyVehicleQuarterly::getReportPeriod)); |
| | | if (ec != null && ec > 0) coverage.add(month); |
| | | energyPreview(period, mode, summary, problems); |
| | |
| | | } |
| | | |
| | | private boolean isEnergyType(String t) { |
| | | return "energySummary".equals(t); |
| | | return "energyQuarterSummary".equals(t) || "energyLeader".equals(t); |
| | | } |
| | | |
| | | /** 按 report_period like 'yyyy-' 统计 1..limit 月中有数据的月份(升序) */ |
| | |
| | | Map<String, ScaleSplitTransport> cumMap = loadCumulativeMap(period); |
| | | ScaleSplitTransport province = getProvinceCumulative(period); |
| | | |
| | | // 当月(第二页):周转量拆分表 MONTH 行(含当月同比) |
| | | // 当月(第二页):③提供合计/规下,规上字段由 ① H203-2 统一覆盖 |
| | | Map<String, Map<Integer, ScaleSplitTransport>> monthData = loadMonthData(period); |
| | | 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); |
| | | for (String city : RegionUtil.cityList()) { |
| | | ScaleSplitTransport rec = getRecord(monthData, city, month); |
| | | if (rec != null) monthTurnover.put(city, rec); |
| | | } |
| | | ScaleSplitTransport provinceMonth = monthTurnover.remove("湖北省"); |
| | | ScaleSplitTransport provinceMonth = loadProvinceMonthMap(period).get(month); |
| | | |
| | | // 以 docs/货运/生成_周转量排名.xlsx 为底稿:保留表头/合并/列宽/样式,仅替换数据;Q/R 占比为模板缓存值,按新数据重算 |
| | | File template = resolveFreightTemplate("生成_周转量排名.xlsx"); |
| | |
| | | int month = parseMonth(record.getReportPeriod()); |
| | | result.computeIfAbsent(city, k -> new HashMap<>()).put(month, record); |
| | | } |
| | | applyH2032MonthlyTurnoverAbove(result, period); |
| | | return result; |
| | | } |
| | | |
| | |
| | | Map<String, ScaleSplitTransport> result = new HashMap<>(); |
| | | List<ScaleSplitTransport> list = scaleSplitMapper.selectList( |
| | | new LambdaQueryWrapper<ScaleSplitTransport>() |
| | | .eq(ScaleSplitTransport::getPeriodType, "CUMULATIVE")); |
| | | .eq(ScaleSplitTransport::getPeriodType, "CUMULATIVE") |
| | | .eq(ScaleSplitTransport::getReportPeriod, period)); // 2026-10-12:只认目标期,缺数留空、不静默回退上一期 |
| | | for (ScaleSplitTransport record : list) { |
| | | if (record.getReportPeriod() == null) continue; |
| | | if (record.getReportPeriod().compareTo(period) > 0) continue; |
| | | if (!period.equals(record.getReportPeriod())) continue; |
| | | String city = RegionUtil.normalizeCityName(record.getRegionName()); |
| | | if (city == null) continue; |
| | | if ("湖北省".equals(city)) continue; |
| | |
| | | result.put(city, record); |
| | | } |
| | | } |
| | | applyH2032CumulativeTurnoverAbove(result, period); |
| | | return result; |
| | | } |
| | | |
| | |
| | | int month = parseMonth(record.getReportPeriod()); |
| | | result.put(month, record); |
| | | } |
| | | applyH2032ProvinceMonthTurnoverAbove(result, period); |
| | | return result; |
| | | } |
| | | |
| | |
| | | private ScaleSplitTransport getProvinceCumulative(String period) { |
| | | List<ScaleSplitTransport> list = scaleSplitMapper.selectList( |
| | | new LambdaQueryWrapper<ScaleSplitTransport>() |
| | | .eq(ScaleSplitTransport::getPeriodType, "CUMULATIVE")); |
| | | .eq(ScaleSplitTransport::getPeriodType, "CUMULATIVE") |
| | | .eq(ScaleSplitTransport::getReportPeriod, period)); // 2026-10-12:同上(只认目标期) |
| | | ScaleSplitTransport best = null; |
| | | for (ScaleSplitTransport record : list) { |
| | | if (record.getReportPeriod() == null) continue; |
| | | if (record.getReportPeriod().compareTo(period) > 0) continue; |
| | | if (!period.equals(record.getReportPeriod())) continue; |
| | | String name = RegionUtil.normalizeCityName(record.getRegionName()); |
| | | if (!"湖北省".equals(name)) continue; |
| | | if (best == null || record.getReportPeriod().compareTo(best.getReportPeriod()) > 0) best = record; |
| | | } |
| | | return best; |
| | | return applyH2032ProvinceCumulativeTurnoverAbove(best, period); |
| | | } |
| | | |
| | | /** H2032规上: city -> month -> 货运量(吨) */ |
| | |
| | | result.merge(city, freight, Double::sum); |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | /** H2032 规上周转量: city -> month -> 万吨公里(turnover_total 吨公里 ÷10000) */ |
| | | private Map<String, Map<Integer, Double>> loadH2032TurnoverByMonth(String period) { |
| | | Map<String, Map<Integer, Double>> result = new HashMap<>(); |
| | | String yearPrefix = period.length() >= 4 ? period.substring(0, 4) : null; |
| | | for (H2032EnterpriseMonthly record : h2032Mapper.selectList(null)) { |
| | | String rp = record.getReportPeriod(); |
| | | if (rp == null || rp.compareTo(period) > 0) continue; |
| | | if (yearPrefix != null && !rp.startsWith(yearPrefix)) continue; |
| | | if (record.getTurnoverTotal() == null) continue; |
| | | String city = RegionUtil.cityByCode(record.getRegionCode()); |
| | | if (city == null) continue; |
| | | int m = parseMonth(rp); |
| | | result.computeIfAbsent(city, k -> new HashMap<>()) |
| | | .merge(m, record.getTurnoverTotal() / 10000.0, Double::sum); |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | /** H2032 规上周转量 1..period 月累计: city -> 万吨公里 */ |
| | | private Map<String, Double> loadH2032TurnoverCumulative(String period) { |
| | | Map<String, Map<Integer, Double>> byMonth = loadH2032TurnoverByMonth(period); |
| | | int target = parseMonth(period); |
| | | Map<String, Double> result = new HashMap<>(); |
| | | for (Map.Entry<String, Map<Integer, Double>> e : byMonth.entrySet()) { |
| | | double sum = 0.0; |
| | | boolean any = false; |
| | | for (int m = 1; m <= target; m++) { |
| | | Double v = e.getValue().get(m); |
| | | if (v != null) { sum += v; any = true; } |
| | | } |
| | | if (any) result.put(e.getKey(), sum); |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | /** 规上字段只认 ① H203-2;③记录只保留合计,并据此重算规下。 */ |
| | | private void applyH2032MonthlyTurnoverAbove(Map<String, Map<Integer, ScaleSplitTransport>> data, |
| | | String period) { |
| | | int lastMonth = parseMonth(period); |
| | | Map<String, Map<Integer, Double>> current = loadH2032TurnoverByMonth(period); |
| | | Map<String, Map<Integer, Double>> prior = loadH2032TurnoverByMonth(previousYearPeriod(period)); |
| | | for (String city : RegionUtil.cityList()) { |
| | | Map<Integer, ScaleSplitTransport> cityData = data.get(city); |
| | | for (int m = 1; m <= lastMonth; m++) { |
| | | ScaleSplitTransport rec = cityData == null ? null : cityData.get(m); |
| | | Double above = monthValueOf(current, city, m); |
| | | if (rec == null && above == null) continue; |
| | | if (cityData == null) { |
| | | cityData = new HashMap<>(); |
| | | data.put(city, cityData); |
| | | } |
| | | if (rec == null) { |
| | | rec = new ScaleSplitTransport(); |
| | | rec.setRegionName(city); |
| | | cityData.put(m, rec); |
| | | } |
| | | applyH2032TurnoverAbove(rec, above, growthYoy(above, monthValueOf(prior, city, m))); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private void applyH2032CumulativeTurnoverAbove(Map<String, ScaleSplitTransport> data, String period) { |
| | | Map<String, Double> current = loadH2032TurnoverCumulative(period); |
| | | Map<String, Double> prior = loadH2032TurnoverCumulative(previousYearPeriod(period)); |
| | | for (String city : RegionUtil.cityList()) { |
| | | Double above = current.get(city); |
| | | ScaleSplitTransport rec = data.get(city); |
| | | if (rec == null && above == null) continue; |
| | | if (rec == null) { |
| | | rec = new ScaleSplitTransport(); |
| | | rec.setRegionName(city); |
| | | data.put(city, rec); |
| | | } |
| | | applyH2032TurnoverAbove(rec, above, growthYoy(above, prior.get(city))); |
| | | } |
| | | } |
| | | |
| | | private void applyH2032ProvinceMonthTurnoverAbove(Map<Integer, ScaleSplitTransport> data, String period) { |
| | | int lastMonth = parseMonth(period); |
| | | Map<String, Map<Integer, Double>> current = loadH2032TurnoverByMonth(period); |
| | | Map<String, Map<Integer, Double>> prior = loadH2032TurnoverByMonth(previousYearPeriod(period)); |
| | | for (int m = 1; m <= lastMonth; m++) { |
| | | Double above = sumCitiesOfMonth(current, m); |
| | | ScaleSplitTransport rec = data.get(m); |
| | | if (rec == null && above == null) continue; |
| | | if (rec == null) { |
| | | rec = new ScaleSplitTransport(); |
| | | rec.setRegionName("湖北省"); |
| | | data.put(m, rec); |
| | | } |
| | | applyH2032TurnoverAbove(rec, above, growthYoy(above, sumCitiesOfMonth(prior, m))); |
| | | } |
| | | } |
| | | |
| | | private ScaleSplitTransport applyH2032ProvinceCumulativeTurnoverAbove(ScaleSplitTransport province, |
| | | String period) { |
| | | Map<String, Double> current = loadH2032TurnoverCumulative(period); |
| | | Map<String, Double> prior = loadH2032TurnoverCumulative(previousYearPeriod(period)); |
| | | Double above = sumCitiesOf(current); |
| | | if (province == null && above == null) return null; |
| | | if (province == null) { |
| | | province = new ScaleSplitTransport(); |
| | | province.setRegionName("湖北省"); |
| | | } |
| | | applyH2032TurnoverAbove(province, above, growthYoy(above, sumCitiesOf(prior))); |
| | | return province; |
| | | } |
| | | |
| | | private void applyH2032TurnoverAbove(ScaleSplitTransport rec, Double above, Double yoy) { |
| | | rec.setAboveScaleTurnover(above); |
| | | rec.setAboveScaleYoy(yoy); |
| | | Double total = rec.getTotalTurnover(); |
| | | rec.setBelowScaleTurnover(total == null || above == null ? null : total - above); |
| | | } |
| | | |
| | | private String previousYearPeriod(String period) { |
| | | return (Integer.parseInt(period.substring(0, 4)) - 1) + period.substring(4); |
| | | } |
| | | |
| | | private Double sumCitiesOf(Map<String, Double> values) { |
| | | Double sum = null; |
| | | for (String city : RegionUtil.cityList()) { |
| | | Double v = values.get(city); |
| | | if (v != null) sum = sum == null ? v : sum + v; |
| | | } |
| | | return sum; |
| | | } |
| | | |
| | | private Double sumCitiesOfMonth(Map<String, Map<Integer, Double>> values, int month) { |
| | | Double sum = null; |
| | | for (String city : RegionUtil.cityList()) { |
| | | Double v = monthValueOf(values, city, month); |
| | | if (v != null) sum = sum == null ? v : sum + v; |
| | | } |
| | | return sum; |
| | | } |
| | | |
| | | private Double monthValueOf(Map<String, Map<Integer, Double>> byMonth, String city, int month) { |
| | | Map<Integer, Double> buckets = byMonth.get(city); |
| | | return buckets == null ? null : buckets.get(month); |
| | | } |
| | | |
| | | /** H2032规上同比(需去年同期的H2032数据,暂无则为空) */ |
| | |
| | | |
| | | // ==================== 5. 生成_能运汇总表(H204 道路货运车辆能源消耗情况) ==================== |
| | | |
| | | /** 燃料类型码 -> 周转量单耗折算系数(千克标准煤折算) */ |
| | | private static final Map<String, Double> ENERGY_FUEL_COEFF = new HashMap<>(); |
| | | /** 汇总表燃料行(顺序与模板一致;混合动力含 05 双燃料/06 混动) */ |
| | | private static final String[] ENERGY_FUEL_ROWS = { |
| | | "柴油车", "汽油车", "液化天然气车", "压缩天然气车", "纯电动车", "混合动力车", "燃料电池车" |
| | | }; |
| | | |
| | | 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_QUARTER_CN = {"一", "二", "三", "四"}; |
| | | |
| | | /** 燃料类型码 -> 汇总表行名 */ |
| | | private static String energyFuelRow(String code) { |
| | | if (code == null) return null; |
| | | switch (code.trim()) { |
| | | case "01": return "汽油车"; |
| | | case "02": return "柴油车"; |
| | | case "03": return "压缩天然气车"; |
| | | case "04": return "液化天然气车"; |
| | | case "05": |
| | | case "06": return "混合动力车"; |
| | | case "07": return "纯电动车"; |
| | | case "08": return "燃料电池车"; |
| | | default: return null; |
| | | } |
| | | } |
| | | |
| | | /** 燃料码 -> 汇总表行名(与模板行顺序一致) */ |
| | | private static final String[][] ENERGY_FUEL_ROWS = { |
| | | {"柴油车", "02"}, |
| | | {"汽油车", "01"}, |
| | | {"液化天然气车", "04"}, |
| | | {"压缩天然气车", "03"}, |
| | | {"纯电动车", "07"}, |
| | | {"燃料电池车", "08"} |
| | | }; |
| | | /** 周转量单耗折算系数(与汇总表公式一致:CNG 1.33,混动按电动 0.1229) */ |
| | | private static double energyCoeff(String rowName) { |
| | | if ("汽油车".equals(rowName)) return 0.73 * 1.4714; |
| | | if ("柴油车".equals(rowName)) return 0.86 * 1.4571; |
| | | if ("压缩天然气车".equals(rowName)) return 1.33; |
| | | if ("液化天然气车".equals(rowName)) return 1.7572; |
| | | if ("纯电动车".equals(rowName) || "混合动力车".equals(rowName)) return 0.1229; |
| | | if ("燃料电池车".equals(rowName)) return 0.3329 * 12.1951; |
| | | return 1.0; |
| | | } |
| | | |
| | | /** 百公里单耗的燃料折算系数:混动/燃料电池的消耗量单位不同,模板公式里带系数 */ |
| | | private static double energyPer100Coeff(String rowName) { |
| | | if ("混合动力车".equals(rowName)) return 0.1229; |
| | | if ("燃料电池车".equals(rowName)) return 0.3329 * 12.1951; |
| | | return 1.0; |
| | | } |
| | | |
| | | /** |
| | | * 能运汇总表:按燃料类型分组汇总,全省 + 各市州各一张 sheet |
| | |
| | | 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] + "季度能耗汇总情况表"; |
| | | String title = period.substring(0, 4) + "年第" + ENERGY_QUARTER_CN[quarter - 1] + "季度能耗汇总情况表"; |
| | | |
| | | 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 fuelRow = energyFuelRow(code); |
| | | if (fuelRow == null) { |
| | | log.warn("H204 汇总未知燃料类型码,跳过:{} 码={}", e.getPlateNo(), code); |
| | | continue; |
| | | } |
| | | province.computeIfAbsent(fuelRow, 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); |
| | | .computeIfAbsent(fuelRow, k2 -> new FuelAgg()).add(e); |
| | | } |
| | | } |
| | | |
| | |
| | | try (InputStream in = new FileInputStream(template); |
| | | XSSFWorkbook wb = new XSSFWorkbook(in)) { |
| | | Sheet base = wb.getSheetAt(0); |
| | | base.getRow(0).getCell(0).setCellValue(title); |
| | | writeCellText(base.getRow(0).getCell(0), 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); |
| | | writeCellText(s.getRow(0).getCell(0), title); |
| | | fillEnergyTemplateSheet(s, agg); |
| | | } |
| | | recalc(wb); |
| | |
| | | } |
| | | } |
| | | |
| | | /** 能耗汇总模板填充:1-based 第3~8行为 柴油/汽油/液化天然/压缩天然/纯电/燃料电池;D/J/L/M 为公式列,仅填数值列 */ |
| | | /** 能耗汇总模板填充:第3~9行为 7 类燃料,D/J/L/M 也直接写算好的值(模板 CNG 行没有公式) */ |
| | | 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]); |
| | | FuelAgg agg = data.get(ENERGY_FUEL_ROWS[i]); |
| | | 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); |
| | | for (int c = 1; c <= 12; c++) setEnergyValue(row, c, null); |
| | | continue; |
| | | } |
| | | setEnergyValue(row, 1, (double) agg.count); |
| | | setEnergyValue(row, 2, agg.totalTonnage); |
| | | setEnergyValue(row, 3, agg.avgTonnage()); |
| | | 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, 9, agg.avgDistance()); |
| | | setEnergyValue(row, 10, agg.fuelConsumption); |
| | | setEnergyValue(row, 11, agg.per100(energyPer100Coeff(ENERGY_FUEL_ROWS[i]))); |
| | | setEnergyValue(row, 12, agg.tonKm(energyCoeff(ENERGY_FUEL_ROWS[i]))); |
| | | } |
| | | } |
| | | |
| | | /** 写能耗数值列:有值写入,无值清空模板样例;公式列(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); |
| | | clearCell(c); |
| | | if (v == null) { |
| | | c.setBlank(); |
| | | } else { |
| | | c.setCellValue(v); |
| | | } |
| | | } |
| | | |
| | | /** 生成季度汇总测试版:以《2026年第二季度道路货运能源消耗汇总表3》为底稿,在 B/C 之间插入所选季度 15 列 */ |
| | | public byte[] exportEnergyQuarterSummary(String period) throws Exception { |
| | | String title = energyQuarterTitle(period); |
| | | Map<String, Map<String, FuelAgg>> cur = loadEnergyRegionAgg(period); |
| | | Map<String, Map<String, FuelAgg>> prev = loadEnergyRegionAgg(shiftPeriod(period, -3)); |
| | | Map<String, Map<String, FuelAgg>> last = loadEnergyRegionAgg(shiftPeriod(period, -12)); |
| | | File template = resolveAnyTemplate(energyTemplateDir, "2026年第二季度道路货运能源消耗汇总表3.xlsx"); |
| | | try (InputStream in = new FileInputStream(template); |
| | | XSSFWorkbook wb = new XSSFWorkbook(in)) { |
| | | Sheet sheet = wb.getSheet("汇总明细"); |
| | | if (sheet == null) sheet = wb.getSheetAt(0); |
| | | int start = findQuarterDataStart(sheet, title); |
| | | if (start < 0) { |
| | | insertEnergyQuarterBlock(sheet, 2, 15, title); |
| | | start = 2; |
| | | } |
| | | fillQuarterBlock(sheet, start, cur, prev, last); |
| | | updateEnergyCompareSheet(wb, period, cur, prev, last); |
| | | recalc(wb); |
| | | return toBytesPreserveFormat(wb); |
| | | } |
| | | } |
| | | |
| | | /** 生成领导版(单季度):以用户改后的模板为底稿,保留固定系数公式,填燃料行 + 各地区合计 */ |
| | | public byte[] exportEnergyLeader(String period) throws Exception { |
| | | String title = energyQuarterTitle(period); |
| | | Map<String, Map<String, FuelAgg>> cur = loadEnergyRegionAgg(period); |
| | | File template = resolveAnyTemplate(energyTemplateDir, "生成_20XX年X月能耗汇总表(领导版).xlsx"); |
| | | try (InputStream in = new FileInputStream(template); |
| | | XSSFWorkbook wb = new XSSFWorkbook(in)) { |
| | | Sheet sheet = wb.getSheetAt(0); |
| | | writeCellText(sheet.getRow(0).getCell(0), title); |
| | | fillLeaderSingleQuarter(sheet, cur); |
| | | recalc(wb); |
| | | return toBytesPreserveFormat(wb); |
| | | } |
| | | } |
| | | |
| | | /** 领导版模板:A=地区、B=燃料(含“合计”行)、C-L 为 10 个字段 */ |
| | | private void fillLeaderSingleQuarter(Sheet sheet, Map<String, Map<String, FuelAgg>> data) { |
| | | List<String> regions = new ArrayList<>(); |
| | | Map<String, Integer> totalRows = new LinkedHashMap<>(); |
| | | Map<String, Map<String, Integer>> fuelRows = new LinkedHashMap<>(); |
| | | String region = null; |
| | | for (int r = 2; r <= sheet.getLastRowNum(); r++) { |
| | | String area = cellString(sheet, r, 0); |
| | | if (area != null && !area.trim().isEmpty()) { |
| | | region = area.trim(); |
| | | regions.add(region); |
| | | totalRows.put(region, r); |
| | | fuelRows.put(region, new LinkedHashMap<String, Integer>()); |
| | | continue; |
| | | } |
| | | if (region == null) continue; |
| | | String fuel = cellString(sheet, r, 1); |
| | | if (fuel == null || fuel.trim().isEmpty() || "合计".equals(fuel.trim())) continue; |
| | | fuelRows.get(region).put(fuel.trim(), r); |
| | | } |
| | | |
| | | // 先填 17 市州,便于全省行用公式汇总 |
| | | for (String reg : regions) { |
| | | if ("全省".equals(reg)) continue; |
| | | Map<String, Integer> rows = fuelRows.get(reg); |
| | | boolean any = false; |
| | | for (Map.Entry<String, Integer> e : rows.entrySet()) { |
| | | FuelAgg agg = aggOf(data, reg, e.getKey()); |
| | | if (agg != null && agg.count > 0) any = true; |
| | | writeLeaderFuelRow(sheet, e.getValue(), e.getKey(), agg); |
| | | } |
| | | writeLeaderTotalRow(sheet, totalRows.get(reg), rows, any); |
| | | } |
| | | |
| | | Map<String, Integer> provRows = fuelRows.get("全省"); |
| | | if (provRows != null) { |
| | | for (Map.Entry<String, Integer> e : provRows.entrySet()) { |
| | | String fuel = e.getKey(); |
| | | List<Integer> cityRows = new ArrayList<>(); |
| | | boolean any = false; |
| | | for (String reg : regions) { |
| | | if ("全省".equals(reg)) continue; |
| | | Integer cr = fuelRows.get(reg).get(fuel); |
| | | if (cr != null) cityRows.add(cr); |
| | | FuelAgg agg = aggOf(data, reg, fuel); |
| | | if (agg != null && agg.count > 0) any = true; |
| | | } |
| | | writeLeaderProvinceFuelRow(sheet, e.getValue(), fuel, cityRows, any); |
| | | } |
| | | writeLeaderTotalRow(sheet, totalRows.get("全省"), provRows, true); |
| | | } |
| | | } |
| | | |
| | | private void writeLeaderFuelRow(Sheet sheet, int r, String fuel, FuelAgg agg) { |
| | | if (agg == null || agg.count == 0) { |
| | | for (int c = 2; c <= 11; c++) setCell(sheet, r, c, null); |
| | | return; |
| | | } |
| | | int x = r + 1; |
| | | setCell(sheet, r, 2, (double) agg.count); |
| | | setCell(sheet, r, 3, agg.totalTonnage); |
| | | setFormula(sheet, r, 4, "D" + x + "/C" + x); |
| | | setCell(sheet, r, 5, agg.totalMileage); |
| | | setCell(sheet, r, 6, agg.freight); |
| | | setCell(sheet, r, 7, agg.turnover); |
| | | setFormula(sheet, r, 8, "H" + x + "/G" + x); |
| | | setCell(sheet, r, 9, agg.fuelConsumption); |
| | | setFormula(sheet, r, 10, "J" + x + "/F" + x + "*100" + leaderPer100Coeff(fuel)); |
| | | setFormula(sheet, r, 11, "J" + x + "/H" + x + "*100*" + leaderTonKmCoeff(fuel)); |
| | | } |
| | | |
| | | private void writeLeaderProvinceFuelRow(Sheet sheet, int r, String fuel, List<Integer> cityRows, boolean any) { |
| | | if (!any || cityRows.isEmpty()) { |
| | | for (int c = 2; c <= 11; c++) setCell(sheet, r, c, null); |
| | | return; |
| | | } |
| | | int x = r + 1; |
| | | setFormula(sheet, r, 2, "SUM(" + leaderRefs("C", cityRows) + ")"); |
| | | setFormula(sheet, r, 3, "SUM(" + leaderRefs("D", cityRows) + ")"); |
| | | setFormula(sheet, r, 4, "D" + x + "/C" + x); |
| | | setFormula(sheet, r, 5, "SUM(" + leaderRefs("F", cityRows) + ")"); |
| | | setFormula(sheet, r, 6, "SUM(" + leaderRefs("G", cityRows) + ")"); |
| | | setFormula(sheet, r, 7, "SUM(" + leaderRefs("H", cityRows) + ")"); |
| | | setFormula(sheet, r, 8, "H" + x + "/G" + x); |
| | | setFormula(sheet, r, 9, "SUM(" + leaderRefs("J", cityRows) + ")"); |
| | | setFormula(sheet, r, 10, "J" + x + "/F" + x + "*100" + leaderPer100Coeff(fuel)); |
| | | setFormula(sheet, r, 11, "J" + x + "/H" + x + "*100*" + leaderTonKmCoeff(fuel)); |
| | | } |
| | | |
| | | private void writeLeaderTotalRow(Sheet sheet, Integer r, Map<String, Integer> fuelRows, boolean any) { |
| | | if (r == null) return; |
| | | if (!any || fuelRows.isEmpty()) { |
| | | for (int c = 2; c <= 11; c++) setCell(sheet, r, c, null); |
| | | return; |
| | | } |
| | | int first = java.util.Collections.min(fuelRows.values()); |
| | | int last = java.util.Collections.max(fuelRows.values()); |
| | | int x = r + 1; |
| | | setFormula(sheet, r, 2, "SUM(C" + (first + 1) + ":C" + (last + 1) + ")"); |
| | | setFormula(sheet, r, 3, "SUM(D" + (first + 1) + ":D" + (last + 1) + ")"); |
| | | setFormula(sheet, r, 4, "D" + x + "/C" + x); |
| | | setFormula(sheet, r, 5, "SUM(F" + (first + 1) + ":F" + (last + 1) + ")"); |
| | | setFormula(sheet, r, 6, "SUM(G" + (first + 1) + ":G" + (last + 1) + ")"); |
| | | setFormula(sheet, r, 7, "SUM(H" + (first + 1) + ":H" + (last + 1) + ")"); |
| | | setFormula(sheet, r, 8, "H" + x + "/G" + x); |
| | | setFormula(sheet, r, 9, "SUM(J" + (first + 1) + ":J" + (last + 1) + ")"); |
| | | setCell(sheet, r, 10, null); |
| | | setCell(sheet, r, 11, null); |
| | | } |
| | | |
| | | private String leaderRefs(String col, List<Integer> rows) { |
| | | StringBuilder sb = new StringBuilder(); |
| | | for (Integer row : rows) { |
| | | if (sb.length() > 0) sb.append(','); |
| | | sb.append(col).append(row + 1); |
| | | } |
| | | return sb.toString(); |
| | | } |
| | | |
| | | private String leaderPer100Coeff(String fuel) { |
| | | if ("混合动力车".equals(fuel)) return "*0.1229"; |
| | | if ("燃料电池车".equals(fuel)) return "*0.3329*12.1951"; |
| | | return ""; |
| | | } |
| | | |
| | | private String leaderTonKmCoeff(String fuel) { |
| | | if ("汽油车".equals(fuel)) return "0.73*1.4714"; |
| | | if ("柴油车".equals(fuel)) return "0.86*1.4571"; |
| | | if ("压缩天然气车".equals(fuel)) return "1.33"; |
| | | if ("液化天然气车".equals(fuel)) return "1.7572"; |
| | | if ("纯电动车".equals(fuel) || "混合动力车".equals(fuel)) return "0.1229"; |
| | | if ("燃料电池车".equals(fuel)) return "0.3329*12.1951"; |
| | | return "1"; |
| | | } |
| | | |
| | | /** 按地区(全省 + 17 市州短名)和燃料行汇总 */ |
| | | private Map<String, Map<String, FuelAgg>> loadEnergyRegionAgg(String period) { |
| | | Map<String, Map<String, FuelAgg>> out = new LinkedHashMap<>(); |
| | | out.put("全省", new HashMap<>()); |
| | | for (String city : RegionUtil.cityList()) out.put(RegionUtil.shortName(city), new HashMap<>()); |
| | | List<EnergyVehicleQuarterly> list = energyMapper.selectList( |
| | | new LambdaQueryWrapper<EnergyVehicleQuarterly>() |
| | | .eq(EnergyVehicleQuarterly::getReportPeriod, period)); |
| | | for (EnergyVehicleQuarterly e : list) { |
| | | String fuelRow = energyFuelRow(e.getFuelTypeCode()); |
| | | if (fuelRow == null) continue; |
| | | out.get("全省").computeIfAbsent(fuelRow, k -> new FuelAgg()).add(e); |
| | | String city = RegionUtil.cityByCode(e.getRegionCode()); |
| | | if (city != null) { |
| | | String shortName = RegionUtil.shortName(city); |
| | | out.computeIfAbsent(shortName, k -> new HashMap<>()) |
| | | .computeIfAbsent(fuelRow, k -> new FuelAgg()).add(e); |
| | | } |
| | | } |
| | | return out; |
| | | } |
| | | |
| | | private String energyQuarterTitle(String period) { |
| | | int year = Integer.parseInt(period.substring(0, 4)); |
| | | int month = parseMonth(period); |
| | | int quarter = (month + 2) / 3; |
| | | return year + "年第" + ENERGY_QUARTER_CN[quarter - 1] + "季度"; |
| | | } |
| | | |
| | | private String shiftPeriod(String period, int months) { |
| | | int year = Integer.parseInt(period.substring(0, 4)); |
| | | int month = parseMonth(period); |
| | | int total = year * 12 + (month - 1) + months; |
| | | return (total / 12) + "-" + pad(total % 12 + 1); |
| | | } |
| | | |
| | | private int findQuarterDataStart(Sheet sheet, String title) { |
| | | Row row = sheet.getRow(0); |
| | | if (row == null) return -1; |
| | | for (Cell cell : row) { |
| | | if (cell.getCellType() == CellType.STRING && title.equals(cell.getStringCellValue().trim())) { |
| | | int col = cell.getColumnIndex(); |
| | | return col == 1 ? 2 : col; |
| | | } |
| | | } |
| | | return -1; |
| | | } |
| | | |
| | | /** 在 C 列前插入 15 列,并把原 B1:Q1 的第一季度标题合并区修正到 R1:AF1 */ |
| | | private void insertEnergyQuarterBlock(Sheet sheet, int start, int width, String title) throws Exception { |
| | | int lastCol = lastColumnIndex(sheet); |
| | | int[] widths = new int[lastCol + 1]; |
| | | for (int c = 0; c <= lastCol; c++) widths[c] = sheet.getColumnWidth(c); |
| | | String oldTitle = cellString(sheet, 0, 1); |
| | | sheet.shiftColumns(start, lastCol, width); |
| | | for (int c = start; c <= lastCol; c++) sheet.setColumnWidth(c + width, widths[c]); |
| | | for (int c = start; c < start + width; c++) sheet.setColumnWidth(c, widths[c]); |
| | | removeMergedIfExists(sheet, 0, 1, start + width - 1); |
| | | removeMergedIfExists(sheet, 0, start + width, start + 2 * width - 1); |
| | | setText(sheet, 0, 1, null); |
| | | int oldStart = start + width; |
| | | setText(sheet, 0, oldStart, oldTitle); |
| | | sheet.addMergedRegion(new CellRangeAddress(0, 0, oldStart, oldStart + width - 1)); |
| | | removeMergedIfExists(sheet, 0, start, start + width - 1); |
| | | sheet.addMergedRegion(new CellRangeAddress(0, 0, start, start + width - 1)); |
| | | setText(sheet, 0, start, title); |
| | | copyBlockStyles(sheet, oldStart, start, width); |
| | | copyHeaderValues(sheet, oldStart, start, width, 1); |
| | | } |
| | | |
| | | /** 领导版在 C 列前插入 10 列;原块自动右移,作为去年同期对比块 */ |
| | | private void insertEnergyLeaderBlock(Sheet sheet, int start, int width, String title, String oldTitle) { |
| | | int lastCol = lastColumnIndex(sheet); |
| | | int[] widths = new int[lastCol + 1]; |
| | | for (int c = 0; c <= lastCol; c++) widths[c] = sheet.getColumnWidth(c); |
| | | sheet.shiftColumns(start, lastCol, width); |
| | | for (int c = start; c <= lastCol; c++) sheet.setColumnWidth(c + width, widths[c]); |
| | | for (int c = start; c < start + width; c++) sheet.setColumnWidth(c, widths[c]); |
| | | removeMergedIfExists(sheet, 0, start, start + width - 1); |
| | | sheet.addMergedRegion(new CellRangeAddress(0, 0, start, start + width - 1)); |
| | | setText(sheet, 0, start, title); |
| | | int oldStart = start + width; |
| | | setText(sheet, 0, oldStart, oldTitle); |
| | | copyBlockStyles(sheet, oldStart, start, width); |
| | | copyHeaderValues(sheet, oldStart, start, width, 1); |
| | | } |
| | | |
| | | private void copyBlockStyles(Sheet sheet, int srcStart, int dstStart, int width) { |
| | | for (int r = 0; r <= sheet.getLastRowNum(); r++) { |
| | | Row row = sheet.getRow(r); |
| | | if (row == null) continue; |
| | | for (int i = 0; i < width; i++) { |
| | | Cell src = row.getCell(srcStart + i); |
| | | if (src == null) continue; |
| | | Cell dst = row.getCell(dstStart + i); |
| | | if (dst == null) dst = row.createCell(dstStart + i); |
| | | dst.setCellStyle(src.getCellStyle()); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private void copyHeaderValues(Sheet sheet, int srcStart, int dstStart, int width, int rowIdx) { |
| | | Row row = sheet.getRow(rowIdx); |
| | | if (row == null) return; |
| | | for (int i = 0; i < width; i++) { |
| | | Cell src = row.getCell(srcStart + i); |
| | | Cell dst = row.getCell(dstStart + i); |
| | | if (dst == null) dst = row.createCell(dstStart + i); |
| | | if (src == null || src.getCellType() != CellType.STRING) { |
| | | clearCell(dst); |
| | | } else { |
| | | writeCellText(dst, src.getStringCellValue()); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private void fillQuarterBlock(Sheet sheet, int start, |
| | | Map<String, Map<String, FuelAgg>> cur, |
| | | Map<String, Map<String, FuelAgg>> prev, |
| | | Map<String, Map<String, FuelAgg>> last) { |
| | | String region = null; |
| | | for (int r = 2; r <= sheet.getLastRowNum(); r++) { |
| | | Row row = sheet.getRow(r); |
| | | if (row == null) continue; |
| | | String area = cellString(sheet, r, 0); |
| | | if (area != null && !area.trim().isEmpty()) region = area.trim(); |
| | | String fuel = cellString(sheet, r, 1); |
| | | if (fuel == null || fuel.trim().isEmpty() || region == null) continue; |
| | | FuelAgg agg = aggOf(cur, region, fuel.trim()); |
| | | FuelAgg p = aggOf(prev, region, fuel.trim()); |
| | | FuelAgg l = aggOf(last, region, fuel.trim()); |
| | | writeQuarterRow(sheet, r, start, agg, p, l, fuel.trim()); |
| | | } |
| | | } |
| | | |
| | | private void writeQuarterRow(Sheet sheet, int rowIdx, int start, FuelAgg agg, FuelAgg prev, FuelAgg last, String fuel) { |
| | | if (agg == null || agg.count == 0) { |
| | | for (int i = 0; i < 15; i++) setCell(sheet, rowIdx, start + i, null); |
| | | return; |
| | | } |
| | | setCell(sheet, rowIdx, start, (double) agg.count); |
| | | setCell(sheet, rowIdx, start + 1, agg.totalTonnage); |
| | | setCell(sheet, rowIdx, start + 2, agg.avgTonnage()); |
| | | setCell(sheet, rowIdx, start + 3, agg.totalMileage); |
| | | setCell(sheet, rowIdx, start + 4, agg.loadedMileage); |
| | | setCell(sheet, rowIdx, start + 5, agg.emptyMileage); |
| | | setCell(sheet, rowIdx, start + 6, agg.freight); |
| | | setCell(sheet, rowIdx, start + 7, agg.turnover); |
| | | setCell(sheet, rowIdx, start + 8, agg.avgDistance()); |
| | | setCell(sheet, rowIdx, start + 9, agg.fuelConsumption); |
| | | double perCoeff = energyPer100Coeff(fuel); |
| | | double per = agg.per100(perCoeff); |
| | | setCell(sheet, rowIdx, start + 10, per); |
| | | setCell(sheet, rowIdx, start + 11, ratio(per, prev == null ? null : prev.per100(perCoeff))); |
| | | setCell(sheet, rowIdx, start + 12, ratio(per, last == null ? null : last.per100(perCoeff))); |
| | | double coeff = energyCoeff(fuel); |
| | | double tonKm = agg.tonKm(coeff); |
| | | setCell(sheet, rowIdx, start + 13, tonKm); |
| | | setCell(sheet, rowIdx, start + 14, ratio(tonKm, last == null ? null : last.tonKm(coeff))); |
| | | } |
| | | |
| | | private void fillLeaderBlock(Sheet sheet, int start, Map<String, Map<String, FuelAgg>> data) { |
| | | String region = null; |
| | | for (int r = 2; r <= sheet.getLastRowNum(); r++) { |
| | | Row row = sheet.getRow(r); |
| | | if (row == null) continue; |
| | | String area = cellString(sheet, r, 0); |
| | | if (area != null && !area.trim().isEmpty()) region = area.trim(); |
| | | String fuel = cellString(sheet, r, 1); |
| | | if (fuel == null || fuel.trim().isEmpty() || region == null) continue; |
| | | FuelAgg agg = aggOf(data, region, fuel.trim()); |
| | | if (agg == null || agg.count == 0) { |
| | | for (int i = 0; i < 10; i++) setCell(sheet, r, start + i, null); |
| | | continue; |
| | | } |
| | | setCell(sheet, r, start, (double) agg.count); |
| | | setCell(sheet, r, start + 1, agg.totalTonnage); |
| | | setCell(sheet, r, start + 2, agg.avgTonnage()); |
| | | setCell(sheet, r, start + 3, agg.totalMileage); |
| | | setCell(sheet, r, start + 4, agg.freight); |
| | | setCell(sheet, r, start + 5, agg.turnover); |
| | | setCell(sheet, r, start + 6, agg.avgDistance()); |
| | | setCell(sheet, r, start + 7, agg.fuelConsumption); |
| | | setCell(sheet, r, start + 8, agg.per100(energyPer100Coeff(fuel.trim()))); |
| | | setCell(sheet, r, start + 9, agg.tonKm(energyCoeff(fuel.trim()))); |
| | | } |
| | | } |
| | | |
| | | private void updateEnergyCompareSheet(XSSFWorkbook wb, String period, |
| | | Map<String, Map<String, FuelAgg>> cur, |
| | | Map<String, Map<String, FuelAgg>> prev, |
| | | Map<String, Map<String, FuelAgg>> last) throws Exception { |
| | | Sheet sheet = wb.getSheet("对比"); |
| | | if (sheet == null) return; |
| | | int year = Integer.parseInt(period.substring(0, 4)); |
| | | Map<String, Map<String, FuelAgg>> q4 = loadEnergyRegionAgg((year - 1) + "-12"); |
| | | Map<String, Map<String, FuelAgg>> q3 = loadEnergyRegionAgg((year - 1) + "-09"); |
| | | Map<String, Map<String, FuelAgg>> q2 = loadEnergyRegionAgg((year - 1) + "-06"); |
| | | setText(sheet, 1, 1, energyQuarterTitle(period)); |
| | | setText(sheet, 1, 4, energyQuarterTitle(shiftPeriod(period, -3))); |
| | | setText(sheet, 1, 5, (year - 1) + "年第四季度"); |
| | | setText(sheet, 1, 6, (year - 1) + "年第三季度"); |
| | | setText(sheet, 1, 7, (year - 1) + "年第二季度"); |
| | | for (int r = 2; r <= sheet.getLastRowNum(); r++) { |
| | | String fuel = cellString(sheet, r, 0); |
| | | if (fuel == null || fuel.trim().isEmpty()) continue; |
| | | Double c = energyPer100(cur, "全省", fuel.trim()); |
| | | Double p = energyPer100(prev, "全省", fuel.trim()); |
| | | Double l = energyPer100(last, "全省", fuel.trim()); |
| | | setCell(sheet, r, 1, c); |
| | | setCell(sheet, r, 2, ratio(c, p)); |
| | | setCell(sheet, r, 3, ratio(c, l)); |
| | | setCell(sheet, r, 4, p); |
| | | setCell(sheet, r, 5, energyPer100(q4, "全省", fuel.trim())); |
| | | setCell(sheet, r, 6, energyPer100(q3, "全省", fuel.trim())); |
| | | setCell(sheet, r, 7, energyPer100(q2, "全省", fuel.trim())); |
| | | } |
| | | } |
| | | |
| | | private Double energyPer100(Map<String, Map<String, FuelAgg>> data, String region, String fuel) { |
| | | FuelAgg agg = aggOf(data, region, fuel); |
| | | return agg == null || agg.count == 0 ? null : agg.per100(energyPer100Coeff(fuel)); |
| | | } |
| | | |
| | | private FuelAgg aggOf(Map<String, Map<String, FuelAgg>> data, String region, String fuel) { |
| | | if (data == null) return null; |
| | | Map<String, FuelAgg> map = data.get(region); |
| | | return map == null ? null : map.get(fuel); |
| | | } |
| | | |
| | | private Double ratio(Double cur, Double base) { |
| | | if (cur == null || base == null || base == 0.0) return null; |
| | | return cur / base - 1.0; |
| | | } |
| | | |
| | | private void setCell(Sheet sheet, int rowIdx, int colIdx, Double value) { |
| | | Row row = sheet.getRow(rowIdx); |
| | | if (row == null) row = sheet.createRow(rowIdx); |
| | | Cell cell = row.getCell(colIdx); |
| | | if (cell == null) cell = row.createCell(colIdx); |
| | | clearCell(cell); |
| | | if (value == null) { |
| | | cell.setBlank(); |
| | | } else { |
| | | cell.setCellValue(value); |
| | | } |
| | | } |
| | | |
| | | private void setFormula(Sheet sheet, int rowIdx, int colIdx, String formula) { |
| | | Row row = sheet.getRow(rowIdx); |
| | | if (row == null) row = sheet.createRow(rowIdx); |
| | | Cell cell = row.getCell(colIdx); |
| | | if (cell == null) cell = row.createCell(colIdx); |
| | | clearCell(cell); |
| | | cell.setCellFormula(formula); |
| | | } |
| | | |
| | | private void setText(Sheet sheet, int rowIdx, int colIdx, String value) { |
| | | Row row = sheet.getRow(rowIdx); |
| | | if (row == null) row = sheet.createRow(rowIdx); |
| | | Cell cell = row.getCell(colIdx); |
| | | if (cell == null) cell = row.createCell(colIdx); |
| | | clearCell(cell); |
| | | if (value == null || value.trim().isEmpty()) { |
| | | cell.setBlank(); |
| | | } else { |
| | | writeCellText(cell, value); |
| | | } |
| | | } |
| | | |
| | | /** 清掉公式/旧值;POI 对公式格 setCellValue 会保留公式,必须先清公式 */ |
| | | private void clearCell(Cell cell) { |
| | | if (cell == null) return; |
| | | if (cell.getCellType() == CellType.FORMULA) { |
| | | cell.setCellFormula(null); |
| | | } |
| | | cell.setBlank(); |
| | | } |
| | | |
| | | /** inlineStr 单元格直接 setCellValue 可能保留旧值,先 setBlank 再写 */ |
| | | private void writeCellText(Cell cell, String value) { |
| | | if (cell == null) return; |
| | | clearCell(cell); |
| | | if (value != null && !value.trim().isEmpty()) cell.setCellValue(value); |
| | | } |
| | | |
| | | private String cellString(Sheet sheet, int rowIdx, int colIdx) { |
| | | Row row = sheet.getRow(rowIdx); |
| | | if (row == null) return null; |
| | | Cell cell = row.getCell(colIdx); |
| | | if (cell == null) return null; |
| | | if (cell.getCellType() == CellType.STRING) return cell.getStringCellValue(); |
| | | if (cell.getCellType() == CellType.NUMERIC) return String.valueOf(cell.getNumericCellValue()); |
| | | return null; |
| | | } |
| | | |
| | | private int lastColumnIndex(Sheet sheet) { |
| | | int last = 0; |
| | | for (int r = 0; r <= sheet.getLastRowNum(); r++) { |
| | | Row row = sheet.getRow(r); |
| | | if (row != null && row.getLastCellNum() > last) last = row.getLastCellNum(); |
| | | } |
| | | return Math.max(0, last - 1); |
| | | } |
| | | |
| | | private void removeMergedIfExists(Sheet sheet, int row, int firstCol, int lastCol) { |
| | | for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--) { |
| | | CellRangeAddress r = sheet.getMergedRegion(i); |
| | | if (r.getFirstRow() == row && r.getLastRow() == row |
| | | && r.getFirstColumn() == firstCol && r.getLastColumn() == lastCol) { |
| | | sheet.removeMergedRegion(i); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private byte[] toBytesPreserveFormat(XSSFWorkbook wb) throws Exception { |
| | | try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { |
| | | wb.write(out); |
| | | wb.close(); |
| | | return out.toByteArray(); |
| | | } |
| | | } |
| | | |
| | | /** 能耗汇总:按燃料类型聚合 */ |
| | |
| | | |
| | | private double nz(Double v) { |
| | | return v == null ? 0.0 : v; |
| | | } |
| | | |
| | | double avgTonnage() { |
| | | return count == 0 ? 0.0 : totalTonnage / count; |
| | | } |
| | | |
| | | double avgDistance() { |
| | | return freight == 0.0 ? 0.0 : turnover / freight; |
| | | } |
| | | |
| | | double per100(double coeff) { |
| | | return totalMileage == 0.0 ? 0.0 : fuelConsumption / totalMileage * 100.0 * coeff; |
| | | } |
| | | |
| | | double tonKm(double coeff) { |
| | | return turnover == 0.0 ? 0.0 : fuelConsumption / turnover * 100.0 * coeff; |
| | | } |
| | | } |
| | | |
| | |
| | | |
| | | private String pad(int m) { |
| | | return m < 10 ? "0" + m : String.valueOf(m); |
| | | } |
| | | |
| | | /** 报表期 yyyy-MM -> 中文年月(2025-06 -> 2025年6月),用于动态文件名 */ |
| | | private String periodCn(String period) { |
| | | if (period == null || period.length() < 7) return period == null ? "" : period; |
| | | int year = Integer.parseInt(period.substring(0, 4)); |
| | | int month = Integer.parseInt(period.substring(5, 7)); |
| | | return year + "年" + month + "月"; |
| | | } |
| | | |
| | | private double round(double v, int scale) { |
| | |
| | | int monthFormulaFilled = summaryWorkbookFiller.ensureMonthFormulas(wb, year, effMonth); |
| | | // 累计同比分母修正:母版把「去年各月」与「去年1-M月累计」辅助列同时计入(重复计/漏当月) |
| | | int cumYoyFixed = summaryWorkbookFiller.repairCumulativeYoyFormulas(wb, year, effMonth); |
| | | // 2026-10-13:累计列 / 累计同比分母按表头重建(根治扩列器早期“累计漏月”的历史欠账) |
| | | int cumRebuilt = summaryWorkbookFiller.repairCumulativeFormulas(wb, year, effMonth); |
| | | reportProgress(progress, 45, "刷新排名页与跨页合成页"); |
| | | int rankRefreshed = refreshSummaryRankSheets(wb, effPeriod, "month"); |
| | | int rankRefreshed = refreshSummaryRankSheets(wb, effPeriod, "month", dbProblems); |
| | | int cumulativeRefreshed = refreshSummaryCumulativeSheets(wb, year, effMonth); // 四张跨页合成页随报表期刷新 |
| | | int widthApplied = applySummaryReferenceLayout(wb); |
| | | // 2026-10-12:停用「套用外部参照件《生成_道路运输量汇总表.xlsx》列宽」——版式一律以当期母版为准, |
| | | // 避免母版与参照件两处维护(母版已并入参照件的列宽/隐藏)。 |
| | | int widthApplied = 0; |
| | | log.info("汇总工作簿数据驱动回填完成:写入当月值格数={},补写当月同比公式格数={},补写当月合计公式格数={}," |
| | | + "修正累计同比分母格数={},刷新排名页数值格数={},刷新四页(城市汇总/城市分市州/中口径分析/道路运输周转量)数值格数={}," |
| | | + "修正累计同比分母格数={},重建累计/累计同比格数={},刷新排名页数值格数={}," |
| | | + "刷新四页(城市汇总/城市分市州/中口径分析/道路运输周转量)数值格数={}," |
| | | + "按《生成_道路运输量汇总表》对齐列宽列数={},缺数提示={}", |
| | | dbFilled, yoyFilled, monthFormulaFilled, cumYoyFixed, rankRefreshed, cumulativeRefreshed, widthApplied, dbProblems); |
| | | dbFilled, yoyFilled, monthFormulaFilled, cumYoyFixed, cumRebuilt, rankRefreshed, cumulativeRefreshed, widthApplied, dbProblems); |
| | | applyTwoDecimalFormat(wb); // 数值显示两位小数(保留全精度);% / 日期等既有样式不改变 |
| | | int inlineFixed = normalizeStaleInlineStrings(wb); // 清掉「非 inlineStr 却残留 <is>」的非法格,否则 Excel 拒绝打开 |
| | | if (inlineFixed > 0) log.warn("汇总工作簿清掉残留 inlineStr 非法格 {} 个(母版由 openpyxl 写出时的典型问题)", inlineFixed); |
| | | reportProgress(progress, 70, "重算整本公式(约 4 万格)"); |
| | | int[] recalc = recalcWorkbookFormulas(wb); // 公式重算并写回缓存值:全省行(Σ市州)/累计列/排名 SUM 才能被预览与二次处理读到 |
| | | setSheetViewsToCurrentMonth(wb, year, effMonth); // 打开时定位到本期数据列(不影响数据与格式) |
| | | log.info("汇总工作簿公式重算完成:成功 {} 格,失败 {} 格(失败格保留母版旧缓存值,打开时按 fullCalcOnLoad 重算)", recalc[0], recalc[1]); |
| | | if (!wb.getCTWorkbook().isSetCalcPr()) wb.getCTWorkbook().addNewCalcPr(); |
| | | wb.getCTWorkbook().getCalcPr().setFullCalcOnLoad(true); // 还原/改写公式后打开即重算 |
| | | appendMissingDataSheet(wb, effPeriod, dbProblems); // 2026-10-12:缺数/体检结果写进生成件(用户要求) |
| | | reportProgress(progress, 95, "写出文件"); |
| | | return toBytes(wb); |
| | | return normalizeSheetViews(toBytes(wb), wb, year, effMonth); |
| | | } finally { |
| | | ZipSecureFile.setMinInflateRatio(savedZipRatio); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 打开工作簿时的定位(2026-10-13):把每个页签的滚动/选中位置归一到「本期数据列」, |
| | | * 并清掉母版(被 Excel/WPS 存过)残留的旧 topLeftCell/activeCell —— 否则每个页签会停在 |
| | | * 上次编辑时的奇怪位置(实测母版里 城市客运 BQ38、中口径明细 CC103、货运排名 A40…)。 |
| | | * 冻结拆分(xSplit/ySplit/state)原样保留,只把锚点挪到本期月份列。 |
| | | */ |
| | | private byte[] normalizeSheetViews(byte[] xlsx, XSSFWorkbook wb, int year, int month) { |
| | | try { |
| | | java.util.Map<String, String> targets = sheetViewTargets(wb, year, month); |
| | | if (targets.isEmpty()) return xlsx; |
| | | java.util.Map<String, byte[]> entries = new java.util.LinkedHashMap<>(); |
| | | try (java.util.zip.ZipInputStream zin = new java.util.zip.ZipInputStream(new java.io.ByteArrayInputStream(xlsx))) { |
| | | java.util.zip.ZipEntry e; |
| | | byte[] buf = new byte[8192]; |
| | | while ((e = zin.getNextEntry()) != null) { |
| | | java.io.ByteArrayOutputStream b = new java.io.ByteArrayOutputStream(); |
| | | int n; |
| | | while ((n = zin.read(buf)) > 0) b.write(buf, 0, n); |
| | | entries.put(e.getName(), b.toByteArray()); |
| | | } |
| | | } |
| | | byte[] wbx = entries.get("xl/workbook.xml"); |
| | | byte[] rlx = entries.get("xl/_rels/workbook.xml.rels"); |
| | | if (wbx == null || rlx == null) return xlsx; |
| | | String wbs = new String(wbx, java.nio.charset.StandardCharsets.UTF_8); |
| | | String rls = new String(rlx, java.nio.charset.StandardCharsets.UTF_8); |
| | | java.util.Map<String, String> rid2t = new java.util.HashMap<>(); |
| | | java.util.regex.Matcher rm = java.util.regex.Pattern.compile("Id=\"([^\"]+)\"[^>]*Target=\"([^\"]+)\"").matcher(rls); |
| | | while (rm.find()) rid2t.put(rm.group(1), rm.group(2)); |
| | | java.util.Map<String, String> name2part = new java.util.LinkedHashMap<>(); |
| | | java.util.regex.Matcher sm = java.util.regex.Pattern.compile("<sheet[^>]*name=\"([^\"]+)\"[^>]*r:id=\"([^\"]+)\"").matcher(wbs); |
| | | while (sm.find()) { |
| | | String t = rid2t.get(sm.group(2)); |
| | | if (t == null) continue; |
| | | if (t.startsWith("/")) t = t.substring(1); |
| | | else if (!t.startsWith("xl/")) t = "xl/" + t; |
| | | name2part.put(sm.group(1), t); |
| | | } |
| | | int patched = 0; |
| | | for (java.util.Map.Entry<String, String> en : name2part.entrySet()) { |
| | | String target = targets.get(en.getKey()); |
| | | byte[] part = entries.get(en.getValue()); |
| | | if (target == null || part == null) continue; |
| | | String xml = new String(part, java.nio.charset.StandardCharsets.UTF_8); |
| | | String np = patchSheetView(xml, target); |
| | | if (!np.equals(xml)) { entries.put(en.getValue(), np.getBytes(java.nio.charset.StandardCharsets.UTF_8)); patched++; } |
| | | } |
| | | try (java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(xlsx.length); |
| | | java.util.zip.ZipOutputStream zout = new java.util.zip.ZipOutputStream(bos)) { |
| | | for (java.util.Map.Entry<String, byte[]> en : entries.entrySet()) { |
| | | zout.putNextEntry(new java.util.zip.ZipEntry(en.getKey())); |
| | | zout.write(en.getValue()); |
| | | zout.closeEntry(); |
| | | } |
| | | zout.finish(); |
| | | log.info("汇总工作簿:页签打开位置已归一到本期({}年{}月),处理 {} 个页签", year, month, patched); |
| | | return bos.toByteArray(); |
| | | } |
| | | } catch (Exception ex) { |
| | | log.warn("汇总工作簿:页签打开位置归一失败(忽略,保留原样):{}", ex.toString()); |
| | | return xlsx; |
| | | } |
| | | } |
| | | |
| | | /** 每页的定位目标:有本期月份列 → 该月表头格;没有(排名/合成页)→ A1(顺带清掉残留位置) */ |
| | | private java.util.Map<String, String> sheetViewTargets(XSSFWorkbook wb, int year, int month) { |
| | | java.util.Map<String, String> m = new java.util.LinkedHashMap<>(); |
| | | for (int i = 0; i < wb.getNumberOfSheets(); i++) { |
| | | XSSFSheet sh = wb.getSheetAt(i); |
| | | if (sh == null) continue; |
| | | int headerRow = -1, col = -1; |
| | | int scan = Math.min(sh.getLastRowNum(), sh.getFirstRowNum() + 4); |
| | | for (int r = sh.getFirstRowNum(); r <= scan && col < 0; r++) { |
| | | Row row = sh.getRow(r); |
| | | if (row == null) continue; |
| | | for (int c = row.getFirstCellNum(); c >= 0 && c < row.getLastCellNum(); c++) { |
| | | Integer ym = smYearMonthOf(row.getCell(c)); |
| | | if (ym != null && ym / 100 == year && ym % 100 == month) { headerRow = r; col = c; break; } |
| | | } |
| | | } |
| | | m.put(sh.getSheetName(), col >= 0 ? a1Ref(headerRow, col) : "A1"); |
| | | } |
| | | return m; |
| | | } |
| | | |
| | | /** 0 基行列 -> "S3" */ |
| | | private String a1Ref(int row0, int col0) { |
| | | StringBuilder sb = new StringBuilder(); |
| | | int n = col0 + 1; |
| | | while (n > 0) { int rem = (n - 1) % 26; sb.insert(0, (char) ('A' + rem)); n = (n - 1) / 26; } |
| | | return sb.toString() + (row0 + 1); |
| | | } |
| | | |
| | | /** 去掉属性 */ |
| | | private String stripAttr(String attrs, String name) { |
| | | int i = attrs.indexOf(name + "=\""); |
| | | if (i < 0) return attrs; |
| | | int e = attrs.indexOf('"', i + name.length() + 2); |
| | | if (e < 0) return attrs; |
| | | return attrs.substring(0, i) + attrs.substring(e + 1); |
| | | } |
| | | |
| | | /** 找标签起点:要求标签名后面紧跟 空格/>,避免 "<sheetView" 命中 "<sheetViews" */ |
| | | private int findTag(String xml, String tag) { |
| | | int from = 0; |
| | | while (true) { |
| | | int i = xml.indexOf(tag, from); |
| | | if (i < 0) return -1; |
| | | int nx = i + tag.length(); |
| | | char ch = nx < xml.length() ? xml.charAt(nx) : '>'; |
| | | if (ch == ' ' || ch == '>' || ch == '/') return i; |
| | | from = i + 1; |
| | | } |
| | | } |
| | | |
| | | /** 取属性值(不存在返回 null) */ |
| | | private String attrValue(String attrs, String name) { |
| | | int i = attrs.indexOf(name + "=\""); |
| | | if (i < 0) return null; |
| | | int e = attrs.indexOf('"', i + name.length() + 2); |
| | | return e < 0 ? null : attrs.substring(i + name.length() + 2, e); |
| | | } |
| | | |
| | | /** 追加属性(已存在则不重复加) */ |
| | | private String addAttr(String attrs, String name, String v) { |
| | | if (attrValue(attrs, name) != null) return attrs; |
| | | String sep = (attrs.isEmpty() || attrs.endsWith(" ")) ? "" : " "; |
| | | return attrs + sep + name + "=\"" + v + "\""; |
| | | } |
| | | |
| | | /** |
| | | * 单页 XML 归一:sheetView / pane 的 topLeftCell、活动 pane 的 selection 全部指向 target。 |
| | | * 冻结拆分(xSplit/ySplit/state)原样保留;破坏结构则返回原文(failed-safe)。 |
| | | */ |
| | | private String patchSheetView(String xml, String target) { |
| | | String orig = xml; |
| | | int i = findTag(xml, "<sheetView"); |
| | | if (i >= 0) { |
| | | int j = xml.indexOf('>', i); |
| | | if (j > 0) { |
| | | // 2026-10-14:滚动起点固定回 A1(只挪光标,不挪视口),否则打开时表头行与左侧列会被滚出视野 |
| | | String attrs = addAttr(stripAttr(xml.substring(i + 10, j), "topLeftCell"), "topLeftCell", "A1"); |
| | | xml = xml.substring(0, i) + "<sheetView" + attrs + ">" + xml.substring(j + 1); |
| | | } |
| | | } |
| | | String activePane = null; |
| | | int p = findTag(xml, "<pane"); |
| | | if (p >= 0) { |
| | | int q = xml.indexOf("/>", p); |
| | | if (q > 0) { |
| | | String raw = xml.substring(p + 5, q); |
| | | activePane = attrValue(raw, "activePane"); |
| | | String attrs = addAttr(stripAttr(raw, "topLeftCell"), "topLeftCell", "A1"); |
| | | xml = xml.substring(0, p) + "<pane" + attrs + "/>" + xml.substring(q + 2); |
| | | } |
| | | } |
| | | StringBuilder sb = new StringBuilder(); |
| | | int last = 0, pos = 0; |
| | | boolean done = false, any = false; |
| | | while (true) { |
| | | int s0 = xml.indexOf("<selection", pos); |
| | | if (s0 < 0) break; |
| | | int s1 = xml.indexOf("/>", s0); |
| | | if (s1 < 0) break; |
| | | String raw = xml.substring(s0 + 10, s1); |
| | | String attrs = stripAttr(stripAttr(raw, "activeCell"), "sqref"); |
| | | String pane = attrValue(raw, "pane"); |
| | | boolean hit = (activePane != null) ? (pane != null && pane.equals(activePane)) : !done; |
| | | if (hit) { attrs = addAttr(addAttr(attrs, "activeCell", target), "sqref", target); done = true; } |
| | | sb.append(xml, last, s0).append("<selection").append(attrs).append("/>"); |
| | | last = s1 + 2; |
| | | pos = s1 + 2; |
| | | any = true; |
| | | } |
| | | if (!any) { |
| | | int close = xml.indexOf("</sheetView>"); |
| | | if (close > 0) xml = xml.substring(0, close) + "<selection activeCell=\"" + target + "\" sqref=\"" + target + "\"/>" + xml.substring(close); |
| | | } else { |
| | | sb.append(xml, last, xml.length()); |
| | | xml = sb.toString(); |
| | | } |
| | | if (!xml.contains("<sheetViews>") || !xml.contains("</sheetViews>")) return orig; |
| | | return xml; |
| | | } |
| | | |
| | | /** |
| | | * 生成件《数据缺失清单》页(2026-10-12,用户要求)。 |
| | | * |
| | | * <p>把本次导出的「缺数清单」与「货运基数体检」结果显式写进产物:用户拿到文件即可看到本报表期 |
| | | * 有哪些数没到、哪些数不合理,不必翻导出日志。只读提示页,不参与本表计算。 |
| | | */ |
| | | private void appendMissingDataSheet(XSSFWorkbook wb, String period, List<String> problems) { |
| | | String sheetName = "数据缺失清单"; |
| | | int old = wb.getSheetIndex(sheetName); |
| | | if (old >= 0) wb.removeSheetAt(old); // 母版由「当期产物」派生时可能已带本页,先移除避免重名 |
| | | XSSFSheet sh = wb.createSheet(sheetName); |
| | | |
| | | CellStyle titleStyle = wb.createCellStyle(); |
| | | Font titleFont = wb.createFont(); |
| | | titleFont.setBold(true); |
| | | titleFont.setFontHeightInPoints((short) 14); |
| | | titleStyle.setFont(titleFont); |
| | | |
| | | CellStyle metaStyle = wb.createCellStyle(); |
| | | Font metaFont = wb.createFont(); |
| | | metaFont.setFontHeightInPoints((short) 10); |
| | | metaFont.setColor(IndexedColors.GREY_50_PERCENT.getIndex()); |
| | | metaStyle.setFont(metaFont); |
| | | |
| | | CellStyle sectionStyle = wb.createCellStyle(); |
| | | Font sectionFont = wb.createFont(); |
| | | sectionFont.setBold(true); |
| | | sectionStyle.setFont(sectionFont); |
| | | |
| | | CellStyle bodyStyle = wb.createCellStyle(); |
| | | bodyStyle.setWrapText(true); |
| | | bodyStyle.setVerticalAlignment(VerticalAlignment.TOP); |
| | | |
| | | List<String> missing = new ArrayList<>(); |
| | | List<String> check = new ArrayList<>(); |
| | | List<String> other = new ArrayList<>(); |
| | | if (problems != null) { |
| | | for (String p : problems) { |
| | | if (p == null || p.trim().isEmpty()) continue; |
| | | if (p.startsWith("缺数")) missing.add(p); |
| | | else if (p.startsWith("货运体检")) check.add(p); |
| | | else other.add(p); |
| | | } |
| | | } |
| | | |
| | | int r = 0; |
| | | Row tRow = sh.createRow(r++); |
| | | Cell tCell = tRow.createCell(0); |
| | | tCell.setCellValue("数据缺失清单"); |
| | | tCell.setCellStyle(titleStyle); |
| | | |
| | | Row mRow = sh.createRow(r++); |
| | | Cell mCell = mRow.createCell(0); |
| | | mCell.setCellValue("报表期 " + period + " 生成时间 " |
| | | + new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").format(new java.util.Date()) |
| | | + " 共 " + (missing.size() + check.size() + other.size()) + " 条"); |
| | | mCell.setCellStyle(metaStyle); |
| | | |
| | | Row nRow = sh.createRow(r++); |
| | | Cell nCell = nRow.createCell(0); |
| | | nCell.setCellValue("本页由程序自动生成(只读提示):一、缺数清单=该有的数没有;二、数据体检=数值不合理(如规下为负)。不参与本表计算。"); |
| | | nCell.setCellStyle(metaStyle); |
| | | |
| | | r++; |
| | | r = writeProblemSection(sh, r, "一、缺数清单(该有的数没有)", missing, sectionStyle, bodyStyle); |
| | | r = writeProblemSection(sh, r, "二、数据体检(数值不合理)", check, sectionStyle, bodyStyle); |
| | | if (!other.isEmpty()) { |
| | | r = writeProblemSection(sh, r, "三、其它提示", other, sectionStyle, bodyStyle); |
| | | } |
| | | |
| | | sh.setColumnWidth(0, 6 * 256); |
| | | sh.setColumnWidth(1, 120 * 256); |
| | | sh.createFreezePane(0, 3); |
| | | } |
| | | |
| | | /** 写一个清单分区(标题 + 逐条),返回下一个可写行号 */ |
| | | private int writeProblemSection(XSSFSheet sh, int rowIdx, String title, List<String> lines, |
| | | CellStyle sectionStyle, CellStyle bodyStyle) { |
| | | Row hr = sh.createRow(rowIdx++); |
| | | Cell hc = hr.createCell(0); |
| | | hc.setCellValue(title); |
| | | hc.setCellStyle(sectionStyle); |
| | | sh.addMergedRegion(new CellRangeAddress(rowIdx - 1, rowIdx - 1, 0, 1)); |
| | | if (lines.isEmpty()) { |
| | | Row er = sh.createRow(rowIdx++); |
| | | er.createCell(0).setCellValue("—"); |
| | | er.createCell(1).setCellValue("无"); |
| | | return rowIdx; |
| | | } |
| | | int i = 1; |
| | | for (String line : lines) { |
| | | Row row = sh.createRow(rowIdx++); |
| | | row.createCell(0).setCellValue(i++); |
| | | Cell c = row.createCell(1); |
| | | c.setCellValue(line); |
| | | c.setCellStyle(bodyStyle); |
| | | } |
| | | return rowIdx; |
| | | } |
| | | |
| | | /** 导出进度回调(异步导出任务用):回调自身异常不影响导出 */ |
| | |
| | | * 的结果刷新数值,避免汇总表里的排名页停留在旧月份。 |
| | | * 数值格搬值、公式格按偏移平移公式后写入;目标格本身已是公式的(SUM/RANK/占比/补数)保留不动,打开时按新数据重算。 |
| | | */ |
| | | private int refreshSummaryRankSheets(XSSFWorkbook wb, String period, String mode) throws Exception { |
| | | private int refreshSummaryRankSheets(XSSFWorkbook wb, String period, String mode, List<String> problems) throws Exception { |
| | | int n = 0; |
| | | n += copyRankValues(wb, "货运量排名", exportFreightRank(period, mode), new int[][]{{0, 0}, {22, 0}}); |
| | | n += copyRankValues(wb, "货运周转量排名", exportTurnoverRank(period, mode), new int[][]{{0, 0}, {22, 0}}); |
| | | n += copyRankValues(wb, "中口径排名", exportPassengerMidRank(period, mode, wb), new int[][]{{0, 0}, {0, 10}}); |
| | | n += copyRankValues(wb, "货运量排名", exportFreightRank(period, mode), new int[][]{{0, 0}, {22, 0}}, problems); |
| | | n += copyRankValues(wb, "货运周转量排名", exportTurnoverRank(period, mode), new int[][]{{0, 0}, {22, 0}}, problems); |
| | | n += copyRankValues(wb, "中口径排名", exportPassengerMidRank(period, mode, wb), new int[][]{{0, 0}, {0, 10}}, problems); |
| | | return n; |
| | | } |
| | | |
| | |
| | | * srcBlocks[i] = 源块 i 的起始 {行, 列}(0 基);目标块按标题顺序(累计块在前、当月块在后)对应。 |
| | | * 数值格直接搬值;源侧是公式的(排名/占比等)按目标块偏移整体平移后写入公式,打开时按汇总表自身数据重算。 |
| | | */ |
| | | private int copyRankValues(XSSFWorkbook dstWb, String dstSheetName, byte[] srcBytes, int[][] srcBlocks) throws Exception { |
| | | private int copyRankValues(XSSFWorkbook dstWb, String dstSheetName, byte[] srcBytes, int[][] srcBlocks, |
| | | List<String> problems) throws Exception { |
| | | XSSFSheet dst = dstWb.getSheet(dstSheetName); |
| | | if (dst == null) return 0; |
| | | List<XSSFCell> dstTitles = rankTitleCells(dst); |
| | | if (dstTitles.isEmpty()) return 0; |
| | | int copied = 0; |
| | | FormulaEvaluator dstEv = dstWb.getCreationHelper().createFormulaEvaluator(); |
| | | List<int[]> anchors = new ArrayList<>(); // {源全省行, 目标全省行, 块首列, 列偏移, 块宽} |
| | | try (InputStream sin = new ByteArrayInputStream(srcBytes); |
| | | XSSFWorkbook srcWb = new XSSFWorkbook(sin)) { |
| | | XSSFSheet src = srcWb.getSheetAt(0); |
| | |
| | | int sr0 = srcBlocks[b][0]; |
| | | int sc0 = srcBlocks[b][1]; |
| | | XSSFCell dstTitle = dstTitles.get(b); |
| | | int rowOff = dstTitle.getRowIndex() - sr0; |
| | | int colOff = dstTitle.getColumnIndex() - sc0; |
| | | int rowOff = dstTitle.getRowIndex() - sr0; |
| | | // 2026-10-13:《货运周转量排名》母版块标题曾占两行(合并),"标题行+固定偏移"会把源行 |
| | | // 整体写错位一行(全省值落到表头行、市州值与市州名错开)。改为用「全省」行做锚点对齐: |
| | | // rowOff = 目标全省行 - 源全省行;识别不到锚点再回退标题行偏移并告警。 |
| | | Integer srcAnchor = rankAnchorRow(src, sr0, sc0); |
| | | Integer dstAnchor = rankAnchorRow(dst, dstTitle.getRowIndex(), dstTitle.getColumnIndex()); |
| | | if (srcAnchor != null && dstAnchor != null) { |
| | | int anchored = dstAnchor - srcAnchor; |
| | | if (anchored != rowOff) { |
| | | log.info("排名页《{}》第 {} 块:标题行偏移 {} 与「全省」锚点偏移 {} 不一致,按锚点对齐(源全省行={},目标全省行={})", |
| | | dstSheetName, b + 1, rowOff, anchored, srcAnchor + 1, dstAnchor + 1); |
| | | } |
| | | rowOff = anchored; |
| | | } else { |
| | | log.warn("排名页《{}》第 {} 块:未识别到「全省」锚点(源={},目标={}),回退按标题行偏移 {} 对齐", |
| | | dstSheetName, b + 1, srcAnchor, dstAnchor, rowOff); |
| | | } |
| | | int h = rankBlockHeight(src, sr0, sc0); |
| | | int w = rankBlockWidth(src, sr0, sc0); |
| | | anchors.add(new int[]{srcAnchor == null ? -1 : srcAnchor, dstAnchor == null ? -1 : dstAnchor, sc0, colOff, w}); |
| | | // 2026-10-12:整块缺数(源侧一个数值都没有,如 9 月缺②③时的周转量排名)→ 目标块只留标题与标签, |
| | | // 数据/排名/占比一律留空;否则母版的 RANK/占比公式会在空块上算出「全 1 + #DIV/0!」。 |
| | | boolean blockHasData = false; |
| | | for (int r = 1; r < h && !blockHasData; r++) { |
| | | Row sr = src.getRow(sr0 + r); |
| | | if (sr == null) continue; |
| | | for (int c = 0; c < w; c++) { |
| | | Cell sc0c = sr.getCell(sc0 + c); |
| | | if (sc0c != null && rankNumeric(sc0c, ev) != null) { |
| | | blockHasData = true; |
| | | break; |
| | | } |
| | | } |
| | | } |
| | | for (int r = 0; r < h; r++) { |
| | | Row srcRow = src.getRow(sr0 + r); |
| | | if (srcRow == null) continue; |
| | | Row dstRow = dst.getRow(sr0 + r + rowOff); |
| | | if (dstRow == null) dstRow = dst.createRow(sr0 + r + rowOff); |
| | | for (int c = 0; c < w; c++) { |
| | | Cell sc = srcRow.getCell(sc0 + c); |
| | | if (sc == null) continue; |
| | | int dc = sc0 + c + colOff; |
| | | Cell sc = srcRow.getCell(sc0 + c); |
| | | if (!blockHasData && r > 0) { |
| | | // 整块缺数:只保留标签(市州名/指标名),数据与排名/占比重算结果一律留空 |
| | | if (sc == null || !isRankLabel(sc)) clearRankCell(dstRow, dc); |
| | | continue; |
| | | } |
| | | if (sc == null) { |
| | | // 2026-10-12:源侧整格缺失 = 缺数 → 目标格按「缺数留空」清空(不再沿用母版上一报表期的旧值) |
| | | if (r > 0) clearRankCell(dstRow, dc); |
| | | continue; |
| | | } |
| | | if (r == 0) { |
| | | // 标题行:同步块标题文案。母版标题是 inlineStr,POI 的 setCellValue 只写 <v>、 |
| | | // 不更新 <is>,Excel 会继续显示旧月份,必须先 setBlank 清掉再写。 |
| | |
| | | continue; |
| | | } |
| | | Double v = rankNumeric(sc, ev); |
| | | if (v == null) continue; |
| | | if (v == null) { |
| | | // 2026-10-12:源侧数值位为空(如缺②全口径时排名表的「规下」列)= 缺数 → 留空; |
| | | // 源侧是标签文本(市州名/指标名)时不是缺数,保留母版自带内容。 |
| | | if (!isRankLabel(sc)) clearRankCell(dstRow, dc); |
| | | continue; |
| | | } |
| | | if (dcCell == null) dcCell = rankCell(dstRow, dc); |
| | | dcCell.setCellValue(v); |
| | | copied++; |
| | | } |
| | | } |
| | | } |
| | | // 2026-10-13 自检:目标「全省」行应与源侧一致(偏移错位、汇总区间不对时报警并写进缺数清单) |
| | | for (int[] an : anchors) { |
| | | if (an[0] < 0 || an[1] < 0) continue; |
| | | Row srr = src.getRow(an[0]); |
| | | Row drr = dst.getRow(an[1]); |
| | | if (srr == null || drr == null) continue; |
| | | int badCols = 0; |
| | | StringBuilder ex = new StringBuilder(); |
| | | for (int c = 0; c < an[4]; c++) { |
| | | Cell sCell = srr.getCell(an[2] + c); |
| | | Cell dCell = drr.getCell(an[2] + c + an[3]); |
| | | Double sv = sCell == null ? null : rankNumeric(sCell, ev); |
| | | Double dv = dCell == null ? null : rankNumeric(dCell, dstEv); |
| | | if (sv == null && dv == null) continue; |
| | | if (sv == null || dv == null || Math.abs(sv - dv) > Math.max(1.0, Math.abs(sv) * 1e-4)) { |
| | | badCols++; |
| | | if (badCols <= 3) { |
| | | if (ex.length() > 0) ex.append(";"); |
| | | ex.append(colLetter(an[2] + c)).append(" 源=").append(sv).append(" 目标=").append(dv); |
| | | } |
| | | } |
| | | } |
| | | if (badCols >= 2) { |
| | | String msg = "排名页《" + dstSheetName + "》「全省」行与源侧不一致(" + badCols + " 列):" + ex; |
| | | log.warn(msg); |
| | | if (problems != null) problems.add("生成校验:" + msg); |
| | | } |
| | | } |
| | | } |
| | | return copied; |
| | | } |
| | |
| | | Cell left = col > 0 ? row.getCell(col - 1) : null; |
| | | if (left != null) c.setCellStyle(left.getCellStyle()); |
| | | return c; |
| | | } |
| | | |
| | | /** |
| | | * 目标格按「缺数留空」清空。 |
| | | * |
| | | * <p>2026-10-12:这里连母版自带的排名/占比公式格一起清(缺数期不显示"上一期残留值 + 全 1 排名 + #DIV/0!"), |
| | | * 与《生成_货运量排名/周转量排名/中口径排名》这些用户日常核对件的空态一致;下期源侧有数时按源侧重写回来。 |
| | | * 文字标签格不动。 |
| | | */ |
| | | private void clearRankCell(Row dstRow, int col) { |
| | | Cell c = dstRow.getCell(col); |
| | | if (c == null) return; |
| | | if (c.getCellType() != CellType.STRING) c.setBlank(); |
| | | } |
| | | |
| | | /** 源侧是否为文字标签(市州名/指标名)——标签不是缺数,不清空目标格 */ |
| | | private boolean isRankLabel(Cell c) { |
| | | if (c.getCellType() != CellType.STRING) return false; |
| | | String v = c.getStringCellValue(); |
| | | if (v == null) return false; |
| | | String x = v.replace(",", "").trim(); |
| | | if (x.isEmpty()) return false; |
| | | try { |
| | | Double.parseDouble(x); |
| | | return false; |
| | | } catch (NumberFormatException ignore) { |
| | | return true; |
| | | } |
| | | } |
| | | |
| | | /** 公式内所有 A1 引用整体平移:列 +dCol、行 +dRow(SUM/RANK 等函数名后接括号不会被匹配) */ |
| | |
| | | } |
| | | |
| | | /** 排名页里的“块标题”单元格(含“全省分市州”的说明文字),按行、列顺序返回 */ |
| | | /** 在 [fromRow, fromRow+40) 范围内、块起始两列里找整格文本为「全省」的行号(0 基);找不到返回 null。 |
| | | * 2026-10-13:排名页块结构可能因母版版式不同而整体上/下移一行,用「全省」行做锚点可自动对齐。 */ |
| | | private Integer rankAnchorRow(Sheet sh, int fromRow, int col0) { |
| | | int last = Math.min(sh.getLastRowNum(), fromRow + 40); |
| | | for (int r = fromRow; r <= last; r++) { |
| | | Row row = sh.getRow(r); |
| | | if (row == null) continue; |
| | | for (int c = Math.max(0, col0); c <= col0 + 1; c++) { |
| | | Cell cell = row.getCell(c); |
| | | if (cell == null || cell.getCellType() != CellType.STRING) continue; |
| | | String v = cell.getStringCellValue(); |
| | | if (v != null && v.replace(" ", "").equals("全省")) return r; |
| | | } |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | private List<XSSFCell> rankTitleCells(Sheet sh) { |
| | | List<XSSFCell> out = new ArrayList<>(); |
| | | for (int r = sh.getFirstRowNum(); r <= sh.getLastRowNum(); r++) { |
| | |
| | | return cols; |
| | | } |
| | | |
| | | /** |
| | | * 打开工作簿时把每个页签定位到「本期数据」位置(2026-10-13 用户要求)。 |
| | | * 做法:凡能按表头识别出「当年当月值列」的页,把活动单元格设到该月表头格;其余页保持默认。 |
| | | * 只影响打开时的滚动/选中位置,不改任何数据与格式。 |
| | | */ |
| | | private int setSheetViewsToCurrentMonth(XSSFWorkbook wb, int year, int month) { |
| | | int n = 0; |
| | | for (int i = 0; i < wb.getNumberOfSheets(); i++) { |
| | | XSSFSheet sh = wb.getSheetAt(i); |
| | | if (sh == null) continue; |
| | | int headerRow = -1, col = -1; |
| | | int scan = Math.min(sh.getLastRowNum(), sh.getFirstRowNum() + 4); |
| | | for (int r = sh.getFirstRowNum(); r <= scan && col < 0; r++) { |
| | | Row row = sh.getRow(r); |
| | | if (row == null) continue; |
| | | for (int c = row.getFirstCellNum(); c >= 0 && c < row.getLastCellNum(); c++) { |
| | | Integer ym = smYearMonthOf(row.getCell(c)); |
| | | if (ym != null && ym / 100 == year && ym % 100 == month) { headerRow = r; col = c; break; } |
| | | } |
| | | } |
| | | if (col < 0) continue; |
| | | sh.setActiveCell(new org.apache.poi.ss.util.CellAddress(headerRow, col)); |
| | | n++; |
| | | } |
| | | if (n > 0) log.info("汇总工作簿:{} 个页签已定位到本期({}年{}月)数据列", n, year, month); |
| | | return n; |
| | | } |
| | | |
| | | /** 表头单元格 -> 年*100+月;只认「YYYY年M月」文本或「某月 1 号」的日期序列号,排除累计/同比/环比 */ |
| | | private Integer smYearMonthOf(Cell c) { |
| | | if (c == null) return null; |
| | |
| | | return null; |
| | | } |
| | | |
| | | /** 汇总表母版定位:仅精确匹配 {year}年{month}月…(P0-P1 骨架期不允许跨月/跨年静默回退, |
| | | * 目标期无对应母版时明确报错,月份扩展规则待 P0 母版定稿后再放开) */ |
| | | /** |
| | | * 汇总表母版定位:先精确匹配 {year}年{month}月道路运输量汇总表.xlsx; |
| | | * 不存在时(2026-10-16 起)**自动用上一期产物扩列生成当期母版并落盘**(扩列后做表头完整性自检+就地补齐), |
| | | * 自动扩列失败则保持原有「明确报错」的行为。跨年(1 月)不自动扩列,仍需人工新开一本。 |
| | | */ |
| | | 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); |
| | | try { |
| | | return resolveAnyTemplate(summaryTemplateDir, name); |
| | | } catch (RuntimeException notFound) { |
| | | File made = autoExpandMother(period, year, month); |
| | | if (made != null) return made; |
| | | throw notFound; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 缺当期母版时自动扩列(2026-10-16):以上一期「产物缓存」为底(取不到则回退上一期母版并告警), |
| | | * 只做版式(当期列留空),扩列后做「表头完整性自检 + 就地补齐」,落盘为 {年}年{月}月道路运输量汇总表.xlsx。 |
| | | * 幂等:目标文件已存在则直接返回、绝不覆盖;任何一步失败都放弃(保持原有报错行为)。 |
| | | */ |
| | | private File autoExpandMother(String period, String year, int month) { |
| | | try { |
| | | if (month <= 1) { |
| | | log.warn("汇总大表自动扩列:{} 为 1 月(跨年),需人工新开一本,已放弃自动扩列", period); |
| | | return null; |
| | | } |
| | | File dir = existingSummaryDir(); |
| | | if (dir == null) { log.warn("汇总大表自动扩列:找不到母版目录,放弃"); return null; } |
| | | String targetName = year + "年" + month + "月道路运输量汇总表.xlsx"; |
| | | File target = new File(dir, targetName); |
| | | if (target.isFile()) return target; |
| | | String prevPeriod = String.format("%04d-%02d", Integer.parseInt(year), month - 1); |
| | | File src = resolveLatestProduct(prevPeriod); |
| | | String srcTag = "产物"; |
| | | if (src == null) { |
| | | try { |
| | | src = resolveAnyTemplate(summaryTemplateDir, year + "年" + (month - 1) + "月道路运输量汇总表.xlsx"); |
| | | } catch (Exception ignore) { src = null; } |
| | | srcTag = "上一期母版"; |
| | | log.warn("汇总大表自动扩列:未找到 {} 的产物缓存,改以{}为底(历史列可能缺该期数据)", prevPeriod, srcTag); |
| | | } |
| | | if (src == null) { log.warn("汇总大表自动扩列:{} 的产物与母版都没有,放弃", prevPeriod); return null; } |
| | | byte[] srcBytes; |
| | | try (java.io.FileInputStream in = new java.io.FileInputStream(src)) { |
| | | srcBytes = org.apache.poi.util.IOUtils.toByteArray(in); |
| | | } |
| | | double savedRatio = ZipSecureFile.getMinInflateRatio(); |
| | | ZipSecureFile.setMinInflateRatio(0.0001); |
| | | byte[] expanded; |
| | | try { |
| | | expanded = summaryLayoutExpander.expand(srcBytes, Integer.parseInt(year), month); |
| | | } finally { |
| | | ZipSecureFile.setMinInflateRatio(savedRatio); |
| | | } |
| | | Object[] fixed = checkAndFixSummaryHeaderGaps(expanded, src); |
| | | byte[] bytes = (byte[]) fixed[0]; |
| | | String note = (String) fixed[1]; |
| | | File tmp = new File(dir, targetName + ".tmp"); |
| | | try (java.io.FileOutputStream out = new java.io.FileOutputStream(tmp)) { out.write(bytes); } |
| | | if (!tmp.renameTo(target)) { |
| | | try (java.io.FileOutputStream out = new java.io.FileOutputStream(target)) { out.write(bytes); } |
| | | tmp.delete(); |
| | | } |
| | | log.warn("汇总大表自动扩列:已生成当期母版 {}(底={} {};表头自检:{})。请核对版式后再批量出表。", |
| | | targetName, srcTag, src.getName(), note); |
| | | return target; |
| | | } catch (Exception e) { |
| | | log.warn("汇总大表自动扩列失败(保持原有报错行为):{}", e.toString()); |
| | | return null; |
| | | } |
| | | } |
| | | |
| | | /** 母版目录:取三个候选根里第一个存在的目录 */ |
| | | private File existingSummaryDir() { |
| | | String rel = summaryTemplateDir; |
| | | while (rel != null && 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 d = new File(root); |
| | | if (d.isDirectory()) return d; |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 表头完整性自检 + 就地补齐(2026-10-16):同一页内以「月份表头最多的那一行」为参考行(big 行), |
| | | * 其它行若也含大量月份表头(≥参考行的 60%,避免把数据行误判成表头行)却缺了其中某些月份: |
| | | * ① 先从**底稿(扩列源文件)同 sheet/行/列**取回(扩列把某格清空时最准); |
| | | * ② 取不到再找**同块参考行**——要求两者在共有列上的月份键完全一致(≥80%),避免把《轨道、轮渡》两块 |
| | | * (2026 年月 / 2025 年月同列)互相串写;找不到同块行就只报告、不改; |
| | | * ③ 已有月份表头的格子**绝不覆盖**。 |
| | | * 返回 {补齐后的字节, 说明文字}。 |
| | | */ |
| | | private Object[] checkAndFixSummaryHeaderGaps(byte[] xlsx, File baseSrc) { |
| | | XSSFWorkbook base = null; |
| | | double savedRatio2 = ZipSecureFile.getMinInflateRatio(); |
| | | try { |
| | | if (baseSrc != null && baseSrc.isFile()) { |
| | | ZipSecureFile.setMinInflateRatio(0.0001); // 产物缓存由 POI 写出,styles 高压缩会触发 Zip-bomb 误报 |
| | | base = new XSSFWorkbook(new java.io.FileInputStream(baseSrc)); |
| | | } |
| | | } catch (Exception be) { |
| | | base = null; |
| | | log.warn("汇总大表自动扩列:读取底稿失败(表头恢复将退化为仅同块行):{}", be.toString()); |
| | | } finally { |
| | | ZipSecureFile.setMinInflateRatio(savedRatio2); |
| | | } |
| | | try (XSSFWorkbook wb = new XSSFWorkbook(new java.io.ByteArrayInputStream(xlsx))) { |
| | | int fromBase = 0, fromSibling = 0; |
| | | List<String> stillMissing = new ArrayList<>(); |
| | | for (int si = 0; si < wb.getNumberOfSheets(); si++) { |
| | | Sheet sh = wb.getSheetAt(si); |
| | | Map<Integer, Map<Integer, String>> hdrRows = new LinkedHashMap<>(); |
| | | for (int r = sh.getFirstRowNum(); r <= sh.getLastRowNum(); r++) { |
| | | Map<Integer, String> m = new HashMap<>(); |
| | | Row row = sh.getRow(r); |
| | | if (row != null) { |
| | | for (int c = row.getFirstCellNum(); c >= 0 && c < row.getLastCellNum(); c++) { |
| | | String k = monthHeaderKey(row.getCell(c)); |
| | | if (k != null) m.put(c, k); |
| | | } |
| | | } |
| | | if (m.size() >= 4) hdrRows.put(r, m); |
| | | } |
| | | if (hdrRows.isEmpty()) continue; |
| | | int bestRow = -1, bestCnt = 0; |
| | | for (Map.Entry<Integer, Map<Integer, String>> en : hdrRows.entrySet()) { |
| | | if (en.getValue().size() > bestCnt) { bestCnt = en.getValue().size(); bestRow = en.getKey(); } |
| | | } |
| | | Map<Integer, String> bestMap = hdrRows.get(bestRow); |
| | | Sheet baseSheet = base == null ? null : base.getSheet(sh.getSheetName()); |
| | | // 2026-10-16:底稿里已是月份表头的格子,扩列后若被写成「别的年份的月份」(双块页如《轨道、轮渡》 |
| | | // 两块同列不同年时会串写),按底稿恢复——正确扩列不应改变既有月份表头;跨年不适用(年内不可能变年)。 |
| | | if (baseSheet != null) { |
| | | for (int r = baseSheet.getFirstRowNum(); r <= baseSheet.getLastRowNum(); r++) { |
| | | Row brow = baseSheet.getRow(r); |
| | | if (brow == null) continue; |
| | | Row orow = sh.getRow(r); |
| | | if (orow == null) continue; |
| | | for (int c = brow.getFirstCellNum(); c >= 0 && c < brow.getLastCellNum(); c++) { |
| | | String bk = monthHeaderKey(brow.getCell(c)); |
| | | if (bk == null) bk = numericSerialKey(brow.getCell(c)); // 底稿日期序列丢格式时兜底 |
| | | if (bk == null) continue; |
| | | Cell oc = orow.getCell(c); |
| | | String ok = monthHeaderKey(oc); |
| | | if (ok == null || ok.equals(bk)) continue; |
| | | if (bk.substring(0, 4).equals(ok.substring(0, 4))) continue; // 同年不动(可能是列位移) |
| | | copyCellValueAndStyle(brow.getCell(c), oc); |
| | | fromBase++; |
| | | } |
| | | } |
| | | } |
| | | for (Map.Entry<Integer, Map<Integer, String>> en : hdrRows.entrySet()) { |
| | | int r = en.getKey(); |
| | | if (r == bestRow) continue; |
| | | Map<Integer, String> mine = en.getValue(); |
| | | if (mine.size() < Math.max(4, (bestCnt * 6) / 10)) continue; |
| | | // 找同块参考行:共有列月份键一致的列数最多、且占比 ≥80% |
| | | int sibRow = -1, sibScore = 0; |
| | | for (Map.Entry<Integer, Map<Integer, String>> en2 : hdrRows.entrySet()) { |
| | | int o = en2.getKey(); |
| | | if (o == r) continue; |
| | | Map<Integer, String> other = en2.getValue(); |
| | | int same = 0; |
| | | for (Map.Entry<Integer, String> e3 : mine.entrySet()) { |
| | | String k2 = other.get(e3.getKey()); |
| | | if (k2 != null && k2.equals(e3.getValue())) same++; |
| | | } |
| | | if (same * 5 >= mine.size() * 4 && same > sibScore) { sibScore = same; sibRow = o; } |
| | | } |
| | | List<String> fixedCols = new ArrayList<>(); |
| | | for (Map.Entry<Integer, String> e3 : bestMap.entrySet()) { |
| | | int col = e3.getKey(); |
| | | Cell cur = sh.getRow(r) == null ? null : sh.getRow(r).getCell(col); |
| | | if (cur != null && monthHeaderKey(cur) != null) continue; // 已有月份表头,绝不覆盖 |
| | | boolean done = false; |
| | | // ① 底稿同位置 |
| | | if (baseSheet != null) { |
| | | Row br = baseSheet.getRow(r); |
| | | Cell bc = br == null ? null : br.getCell(col); |
| | | if (bc != null && monthHeaderKey(bc) != null) { |
| | | Cell dst = cur != null ? cur : sh.getRow(r).createCell(col); |
| | | copyCellValueAndStyle(bc, dst); |
| | | fromBase++; fixedCols.add(e3.getValue()); done = true; |
| | | } |
| | | } |
| | | // ② 同块参考行 |
| | | if (!done && sibRow >= 0) { |
| | | Row sr = sh.getRow(sibRow); |
| | | Cell sc = sr == null ? null : sr.getCell(col); |
| | | if (sc != null && monthHeaderKey(sc) != null) { |
| | | Cell dst = cur != null ? cur : sh.getRow(r).createCell(col); |
| | | copyCellValueAndStyle(sc, dst); |
| | | fromSibling++; fixedCols.add(e3.getValue()); done = true; |
| | | } |
| | | } |
| | | if (!done) { /* 无法安全补齐 */ } |
| | | } |
| | | if (!fixedCols.isEmpty()) { |
| | | for (String k : fixedCols) { |
| | | for (Map.Entry<Integer, String> e3 : bestMap.entrySet()) { |
| | | if (!k.equals(e3.getValue())) continue; |
| | | Cell c2 = sh.getRow(r).getCell(e3.getKey()); |
| | | Cell c3 = sh.getRow(r).getCell(e3.getKey() + 1); |
| | | if (c3 != null && c3.getCellType() == CellType.BLANK && bestMap.containsKey(e3.getKey())) { |
| | | Row br2 = bestRow >= 0 ? sh.getRow(bestRow) : null; |
| | | Cell r2 = br2 == null ? null : br2.getCell(e3.getKey() + 1); |
| | | if (r2 != null && r2.getCellType() != CellType.BLANK) copyCellValueAndStyle(r2, c3); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | } |
| | | } |
| | | baseSafeClose(base); |
| | | int fixed = fromBase + fromSibling; |
| | | if (fixed == 0) return new Object[]{xlsx, stillMissing.isEmpty() ? "无缺失" : "仍缺:" + String.join(";", stillMissing)}; |
| | | ByteArrayOutputStream bos = new ByteArrayOutputStream(xlsx.length); |
| | | wb.write(bos); |
| | | String note = "补齐 " + fixed + " 处表头(底稿 " + fromBase + " / 同块行 " + fromSibling + ")" |
| | | + (stillMissing.isEmpty() ? "" : ";仍有无法安全补齐的缺格(见日志)"); |
| | | return new Object[]{bos.toByteArray(), note}; |
| | | } catch (Exception e) { |
| | | baseSafeClose(base); |
| | | return new Object[]{xlsx, "自检失败(忽略):" + e}; |
| | | } |
| | | } |
| | | |
| | | private void baseSafeClose(XSSFWorkbook b) { |
| | | try { if (b != null) b.close(); } catch (Exception ignore) { } |
| | | } |
| | | |
| | | /** 数值型 Excel 日期序列(20000~60000,即 1954~2064 年)→ "YYYY-MM";非该区间返回 null。 |
| | | * 仅用于「底稿无日期格式但其实是月份表头」的兜底比对。 */ |
| | | private String numericSerialKey(Cell c) { |
| | | if (c == null || c.getCellType() != CellType.NUMERIC) return null; |
| | | double v = c.getNumericCellValue(); |
| | | if (v < 20000 || v > 60000) return null; |
| | | java.util.Date d = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v); |
| | | java.util.Calendar cal = java.util.Calendar.getInstance(); |
| | | cal.setTime(d); |
| | | return String.format("%04d-%02d", cal.get(java.util.Calendar.YEAR), cal.get(java.util.Calendar.MONTH) + 1); |
| | | } |
| | | |
| | | /** 月份表头识别:日期单元格(含日期序列)或 "YYYY年M月" 文本 → 归一化键,否则 null */ |
| | | private String monthHeaderKey(Cell c) { |
| | | if (c == null) return null; |
| | | CellType t = c.getCellType(); |
| | | if (t == CellType.NUMERIC && org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(c)) { |
| | | java.util.Date d = c.getDateCellValue(); |
| | | if (d == null) return null; |
| | | java.util.Calendar cal = java.util.Calendar.getInstance(); |
| | | cal.setTime(d); |
| | | return String.format("%04d-%02d", cal.get(java.util.Calendar.YEAR), cal.get(java.util.Calendar.MONTH) + 1); |
| | | } |
| | | if (t == CellType.STRING) { |
| | | String v = c.getStringCellValue(); |
| | | if (v == null) return null; |
| | | String s = v.replace(" ", ""); |
| | | if (s.endsWith("月") && s.contains("年") && s.length() <= 12) return s; |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | /** 克隆单元格的值与样式(表头补齐用) */ |
| | | private void copyCellValueAndStyle(Cell src, Cell dst) { |
| | | if (src == null || dst == null) return; |
| | | switch (src.getCellType()) { |
| | | case STRING: dst.setCellValue(src.getStringCellValue()); break; |
| | | case NUMERIC: |
| | | if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(src)) dst.setCellValue(src.getDateCellValue()); |
| | | else dst.setCellValue(src.getNumericCellValue()); |
| | | break; |
| | | case FORMULA: dst.setCellFormula(src.getCellFormula()); break; |
| | | default: dst.setBlank(); |
| | | } |
| | | dst.setCellStyle(src.getCellStyle()); |
| | | } |
| | | |
| | | // ==================== 网约车客运量拆分表(月度) ==================== |
| | |
| | | if (data != null) { |
| | | String name = REPORT_FILE_NAMES.get(t); |
| | | if (name == null) name = "生成_" + t + ".xlsx"; |
| | | name = name.replace("{periodCN}", periodCn(period)); |
| | | addZipEntry(zos, name, data); |
| | | } |
| | | } |
| | |
| | | case "passengerMidRank": return exportPassengerMidRank(period, mode); |
| | | case "passengerMidAnalysis": return exportPassengerMidAnalysis(period, mode); |
| | | case "summaryWorkbook": return exportSummaryWorkbook(period, mode); |
| | | case "energySummary": return exportEnergySummary(period); |
| | | case "energyQuarterSummary": return exportEnergyQuarterSummary(period); |
| | | case "energyLeader": return exportEnergyLeader(period); |
| | | case "investPlan": return investPlan(period, mode); |
| | | case "investFiveYearLogistics": return investFiveYearLogistics(period, mode); |
| | | case "investBillion": return investBillion(period, mode); |
| | |
| | | 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("energyQuarterSummary", "生成_{periodCN}能运汇总表.xlsx"); |
| | | REPORT_FILE_NAMES.put("energyLeader", "生成_{periodCN}能耗汇总表(领导版).xlsx"); |
| | | REPORT_FILE_NAMES.put("investPlan", "生成_全省预安排计划进度情况汇总.xls"); |
| | | REPORT_FILE_NAMES.put("investFiveYearLogistics", "生成_十五五规划物流项目进展情况.xls"); |
| | | REPORT_FILE_NAMES.put("investBillion", "生成_湖北省(客货站场)亿元投资项目.xls"); |