package com.nantian.cloud.jljc.tools;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.nantian.cloud.jljc.controller.DevInfoController;
import com.nantian.cloud.jljc.entity.*;
import com.nantian.cloud.jljc.service.DictRegionService;
import com.nantian.cloud.jljc.service.UseEngergyService;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import org.apache.http.client.utils.DateUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jolokia.converter.json.ObjectToJsonConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Excel工具类
 *
 * @author 李鹏
 * @ClassName: LpExcelUtil
 * @date 2022-05-11
 */
public class LpExcelUtil {
    public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
    public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";

    public static final String patten = "yyyy-MM-dd";

    @Autowired
    UseEngergyService useEngergyService;

    // zstb_info 表的导出字段列表, 不包含序号列
//    private static String[] infoFields = {"name", "projectCode", "enterpriseName", "area", "industryCode",
//            "industryType", "lgIndustryCode", "startDate", "produceDate", "checkUnit",
//            "checkFinishDate", "checkFileCode", "investment", "outputValue", "ZhnhDlValue", "zhnhDjValue", "result",
//            "electricValue", "coalValue", "remarks"};
    private static String[] infoFields = {"name", "projectNature", "projectCode", "enterpriseName", "area", "industryCode", "industryType",
            "lgIndustryCode", "constructionContent", "mainProduct", "startOrNot", "projectProgress", "startAndEndTime", "produceDate", "checkUnit", "checkFinishDate",
            "checkFileCode", "investment", "ZhnhDlValue", "zhnhDjValue", "energyConsumption",
            "industrialAddValue", "designPowerLoad", "annualPowerConsumption", "kilowattHourOutputValue", "coalValue", "remarks"};
//    private static String[] infoFieldsName = {"项目名称", "项目代码", "建设单位", "所在州市", "行业代码",
//            "行业类别", "“两高”行业代码", "开工时间", "拟投产时间", "节能审查机关",
//            "审查完成时间", "审查意见文号", "投资金额","工业总产值","年综合能源消费量当量值", "年综合能源消费量等价值", "节能效果",
//            "电力消耗量", "煤炭消费量", "备注"};
    private static String[] infoFieldsName = {"项目名称", "项目性质", "项目代码", "建设单位", "所在州县（市、区）", "行业代码", "行业类别",
            "“两高”行业代码", "建设内容", "主要产品", "是否已开工（是/否）", "项目进度", "建设起止时间", "拟投产时间", "节能审查机关", "审查意见批复时间",
            "审查意见文号", "项目总投资（万元）", "年综合能源消费量（吨标准煤）当量值", "年综合能源消费量（吨标准煤）等价值", "原料用能消费量（吨标准煤）",
            "单位工业增加值能耗（吨标准煤/万元）", "设计用电负荷（万kW）", "年设计用电量（万kWh）", "度电产值（元/kWh）", "煤炭消费量（吨标准煤）", "备注"};
    // 副表 zstb_produce的导出字段列表
    private static String[] produceFields =
            {"productName", "unit", "designOutput", "curYearMonthOutput", "curYearMonthEnergy", "remarks"};
    private static String[] produceFieldsName =
            {"产品名称","单位", "设计产能（吨）", "x年X月产量（吨）", "x年X月对应能源消费量（吨标准煤）", "备注"};
    // zstb_use_engergy表的导出字段列表，不包含序号
    private static String[] engergyFields =
            {"enterpriseName", "enterpriseCode", "industryCode", "area", "lastYearElv", "lastYearEv",
                    "curYearMonthElv", "curYearMonthEv", "dateSectionElv", "dateSectionEv", "lastMonthElectricValue"};
    private static String[] engergyFieldsName = {
            "企业名称", "统一社会信用代码", "行业代码", "所在地市", "年综合能源消费量当量值", "年综合能源消费量等价值",
            "2022年X月综合能源消费量当量值", "2022年X月综合能源消费量等价值", "2022年1－X月综合能源消费量当量值", "2022年1－X月综合能源消费量等价值", "2021年X月耗电量（万千瓦时）"
    };

//    private static String[] stockFields =
//            {"enterpriseCode", "enterpriseName", "itemName", "itemLocation", "industryClassName", "industrySubclassCode",
//                    "enterpriseState", "energyOffice", "energyTime", "energyNumber", "productionTotal", "energyRaw", "energyRawValue",
//                    "productName","productUnit", "capacityDesign", "productOutput1", "productOutput2", "productOutput3", "productOutput4", "productOutput5",
//                    "energyConsumptionLastTwoDl", "energyConsumptionLastTwoDj", "energyConsumptionLastDl", "energyConsumptionLastDj", "remark"};
//    private static String[] stockFieldsName =
//            {"社会信用代码", "企业名称", "项目名称", "所在地", "行业类别", "行业代码",
//                    "企业运行状态", "节能审查机关", "审查完成时间", "节能审查批复文号", "工业总产值", "是否存在原料用能", "若是，原料用能",
//                    "产品名称", "产品单位", "设计产能", "2021年实际产量", "2022年预计实际产量", "2023年预计实际产量", "2024年预计实际产量", "2025年预计实际产量",
//                    "2020年综合能源消费量当量值", "2020年综合能源消费量等价值", "2021年综合能源消费量当量值", "2021年综合能源消费量等价值", "备注"};

    private static String[] stockFieldsCl =
            {"organizationCode", "enterpriseCode", "enterpriseName", "itemLocation", "industryClassName", "industryTypeCode", "industrySubclassCode", "itemName",
                    "enterpriseState", "energyOfficeAndNumber", "energyTime", "productionTotal", "energyRaw", "actualQuantity", "reducedScalar",
                    "productName", "indicatorName", "productUnit", "productUnitConsumption", "limitStandard", "energyEfficiencyLevel", "energyOutputValue", "energyAddedValue",
                    "capacityDesign", "productOutput1", "productOutput2", "thisMonthThisYear", "januaryToThisMonth", "energyThisMonth",
                    "energyJanuaryToThisMonth", "electricThisMonth", "electricJanuaryToThisMonth", "electricityPrice", "productOutput",
                    "energyConsumptionLastTwoDl", "energyConsumptionLastTwoDj", "energyConsumptionLastDl", "energyConsumptionLastDj", "energyConsumptionDl", "energyConsumptionDj",
                    "ministryState", "ecologyState", "remark"};

    private static String[] stockFieldsNameCl =
            {"组织机构代码", "统一社会信用代码", "企业名称", "所在州市", "产业类别", "“两高”行业代码（大类）", "行业代码（小类）", "项目名称",
                    "企业运行状态（正常生产/停产）", "节能审查机关及批复文号", "审查完成时间", "工业总产值(当年价)(万元)", "是否存在原料用能（是/否）", "实物量（万吨）", "折标量（万吨标准煤）",
                    "产品/工序", "产品单耗指标名称", "产品单耗指标单位", "产品单耗指标", "国家能耗限额标准", "能效水平", "产值能耗（吨标准煤/万元）", "增加值能耗（吨标准煤/万元）",
                    "设计产能（吨/千瓦时/重量箱等）", "2021年实际产量（吨/千瓦时/重量箱等）", "2022年实际产量（吨/千瓦时/重量箱等）", "本年度本月产量", "本年度1-本月产量", "本年度本月综合能源消费量（万吨标准煤）当量值",
                    "本年度1－本月综合能源消费量（万吨标准煤）当量值", "本年度本月耗电量（万千瓦时）", "本年度1-本月耗电量（万千瓦时）", "度电增加值(元)", "本年度预计产量（吨/千瓦时/重量箱等）",
                    "2020年综合能源消费量当量值", "2020年综合能源消费量等价值", "2021年综合能源消费量当量值", "2021年综合能源消费量等价值","2022年综合能源消费量当量值", "2022年综合能源消费量等价值",
                    "工业和信息化厅确认是/否属于高耗能项目", "生态环境厅确认是/否属于高排放项目", "备注"};

//    private static String[] stockFieldsOther =
//            {"itemLocation", "industryClassName", "industryTypeCode", "itemName", "enterpriseName", "enterpriseState",
//                    "energyOffice", "energyTime", "energyNumber", "productionTotal", "startTime", "productionTime", "itemInvest",
//                    "energyRaw", "energyRawValue", "productName","productUnit", "capacityDesign", "productOutput2", "productOutput3", "productOutput4", "productOutput5",
//                    "energyDesignDl", "energyDesignDj", "energyNewPlanDl", "energyNewPlanDj", "energySavingEffect", "energyElectricity", "energyCoal", "remark"};
//    private static String[] stockFieldsOtherName =
//            {"所在地", "行业类别", "行业代码", "项目名称", "建设单位", "项目状态",
//                    "节能审查机关", "审查完成时间", "节能审查批复文号", "工业总产值", "开工时间", "投产时间", "项目总投资",
//                    "是否存在原料用能", "若是，原料用能", "主要产品", "产品单位","设计产能", "2022年预计产能", "2023年预计产能", "2024年预计产能", "2025年预计产能",
//                    "设计能耗当量值", "设计能耗等价值", "“十四五” 新增能耗当量值", "十四五” 新增能耗等价值", "节能效果", "电力消耗量", "煤炭消费量", "备注"};

    private static String[] stockFieldsZj =
            {"itemLocation", "industryClassName", "industryTypeCode", "industrySubclassCode", "itemName", "enterpriseCode", "enterpriseName", "enterpriseState",
                    "energyOfficeAndNumber", "energyTime", "productionTotal", "startTime", "productionTime", "itemInvest", "completedInvestment",
                    "energyRaw", "actualQuantity", "reducedScalar", "increment", "productName", "capacityDesign",
                    "energyDesignDl", "energyDesignDj", "energyNewPlanDl", "energyNewPlanDj", "productEnergy", "energySavingEffect", "energyElectricity",
                    "energyCoal", "limitStandard", "energyEfficiencyLevel", "documentNumber", "previousSituation", "capacityReplacement", "remark"};

    private static String[] stockFieldsNameZj =
            {"所在地", "产业类别", "“两高”行业代码（大类）", "行业代码（小类）", "项目名称", "统一社会信用代码", "建设单位", "项目状态",
                    "节能审查机关及批复文号", "审查完成时间", "工业总产值(当年价格)(万元)", "开工时间", "投产时间", "项目总投资（万元）", "已完成投资（万元）",
                    "是否存在原料用能（是/否）", "实物量（万吨）", "折标量（万吨标准煤）", "“十四五”期间新增原料用能消费量（万吨标准煤）", "主要产品", "设计产能（吨/千瓦时/重量箱等）",
                    "设计能耗当量值", "设计能耗等价值", "“十四五” 新增能耗当量值", "十四五” 新增能耗等价值", "单位产品能耗（千克标准煤/吨等）", "节能效果（吨标准煤）", "电力消耗量（万千瓦时)",
                    "煤炭消费量（万吨标准煤）", "国家能耗限额标准", "能效水平", "环评审批机关及批复文号", "项目上马前期论证情况", "产能置换情况", "备注"};


    private static String[] stockFieldsNj =
            {"itemLocation", "industryClassName", "industryTypeCode", "industrySubclassCode",  "itemName", "enterpriseCode", "enterpriseName", "enterpriseState",
                    "energyOfficeAndNumber", "energyTime", "productionTotal", "startTime", "productionTime", "itemInvest",
                    "energyRaw", "energyRawValue", "increment", "productName", "capacityDesign",
                    "energyDesignDl", "energyDesignDj", "energyNewPlanDl", "energyNewPlanDj", "productEnergy", "energyElectricity",
                    "energyCoal", "limitStandard", "energyEfficiencyLevel", "projectLocated", "documentNumber", "previousSituation", "capacityReplacement", "remark"};

    private static String[] stockFieldsNameNj =
            {"所在地", "产业类别", "“两高”行业代码（大类）", "行业代码（小类）", "项目名称", "统一社会信用代码",  "建设单位", "项目状态",
                    "节能审查机关及批复文号", "审查完成时间", "工业总产值(当年价格)(万元)", "预计开工时间", "预计投产时间", "预计项目总投资（万元）",
                    "是否存在原料用能（是/否）", "年设计原料用能消费量", "“十四五”期间新增原料用能消费量", "产品", "设计产能（吨/千瓦时/重量箱等）",
                    "设计能耗当量值", "设计能耗等价值", "“十四五” 新增能耗当量值", "十四五” 新增能耗等价值", "单位产品能耗（千克标准煤/吨等）", "预计电力消耗量（万千瓦时)",
                    "煤炭消费量（万吨标准煤）", "国家能耗限额标准", "能效水平","项目是否位于大气污染防治重点区域内","环评审批机关及批复文号","项目上马前期论证情况", "产能置换情况", "备注"};




    /*
     * 重点企业用能情况表 模板导出
     * */
    public static void useEngergyTemplate(String fileName, HttpServletRequest request, HttpServletResponse response, String[] capacityAvi, String date, String[] unitAvi) throws Exception {
        int year = Integer.parseInt(date.split("-")[0]);
        int month = Integer.parseInt(date.split("-")[1]);
        HSSFWorkbook wb = null;
        try {
            wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("sheet1");
            // 字体
            // 附件二字体
            Font headerFont0 = wb.createFont();
            headerFont0.setFontName("方正黑体_GBK");
            headerFont0.setFontHeightInPoints((short) 12);
            headerFont0.setColor(HSSFColor.BLACK.index);
            // XX州（市）重点企业用能情况表字体
            Font headerFont1 = wb.createFont();
            headerFont1.setFontName("方正小标宋_GBK");
            headerFont1.setFontHeightInPoints((short) 20);
            headerFont1.setColor(HSSFColor.BLACK.index);
            // 填报情况字体
            Font font3 = wb.createFont();
            font3.setFontName("方正仿宋_GBK");
            font3.setFontHeightInPoints((short) 10);
            // 表头字体
            Font font4 = wb.createFont();
            font4.setFontName("方正黑体_GBK");
            font4.setFontHeightInPoints((short) 9);

            // 单元格样式
            // 附件二样式
            CellStyle headerStyle0 = wb.createCellStyle();
            headerStyle0.setFont(headerFont0);
            headerStyle0.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            // XX州（市）重点企业用能情况表样式
            CellStyle headerStyle1 = wb.createCellStyle();
            headerStyle1.setFont(headerFont1);
            headerStyle1.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            headerStyle1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            headerStyle1.setLocked(true);
            headerStyle1.setWrapText(false);// 自动换行
            // 填报情况样式
            CellStyle style1 = wb.createCellStyle();
            style1.setFont(font3);
            style1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style1.setWrapText(true);// 自动换行
            style1.setBorderBottom(BorderStyle.THIN); //下边框
            style1.setBorderLeft(BorderStyle.THIN);//左边框
            style1.setBorderTop(BorderStyle.THIN);//上边框
            style1.setBorderRight(BorderStyle.THIN);//右边框
            // 表内文字样式
            CellStyle style2 = wb.createCellStyle();
            style2.setFont(font4);
            style2.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            style2.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style2.setBorderBottom(BorderStyle.THIN); //下边框
            style2.setBorderLeft(BorderStyle.THIN);//左边框
            style2.setBorderTop(BorderStyle.THIN);//上边框
            style2.setBorderRight(BorderStyle.THIN);//右边框
            style2.setWrapText(true);// 自动换行


//            String[] capacityAvi = {"昆明,530100","五华区,530111"};
            //需要被设置为下拉数据的单元格范围
            CellRangeAddressList capacityList = new CellRangeAddressList(3, 5000, 4, 4);
            // 设置辅修下拉框数据
            DataValidationHelper helper = sheet.getDataValidationHelper();
            DataValidationConstraint capacityConstraint = helper.createExplicitListConstraint(capacityAvi);
            DataValidation capacityDataValidation = helper.createValidation(capacityConstraint, capacityList);
            sheet.addValidationData(capacityDataValidation);

            CellRangeAddressList capacityList1 = new CellRangeAddressList(3, 5000, 13, 13);
            DataValidationHelper helper1 = sheet.getDataValidationHelper();
            DataValidationConstraint capacityConstraint1 = helper1.createExplicitListConstraint(unitAvi);
            DataValidation capacityDataValidation1 = helper1.createValidation(capacityConstraint1, capacityList1);
            sheet.addValidationData(capacityDataValidation1);


            int row = 0;
            // 设置列宽
            for (int i = 0; i < 18; i++) {
                if (i == 0) {
                    sheet.setColumnWidth(i, 1000);
                } else {
                    sheet.setColumnWidth(i, 2900);
                }
            }
            //第一行
            Row r0 = sheet.createRow(row++);
            r0.setHeight((short) 462);//行高
            //第一行第一列
            Cell c00 = r0.createCell(0);
            c00.setCellValue("附件二");
            c00.setCellStyle(headerStyle0);
            //合并单元格（从左到右依次：要合并的初始行位置、结束行位置，初始列位置、结束列位置）
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));

            //第2行
            Row r1 = sheet.createRow(row++);
            r1.setHeight((short) 768);//行高
            //第2行第一列
            Cell c10 = r1.createCell(0);
            c10.setCellValue("XX州（市）重点企业用能情况表");
            c10.setCellStyle(headerStyle1);
            //合并单元格（从左到右依次：要合并的初始行位置、结束行位置，初始列位置、结束列位置）
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 16));
            //第3、4行
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 0));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 1, 1));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 2, 2));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 3, 3));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 4, 4));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 5, 6));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 7, 8));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 9, 10));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 11, 11));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 12, 16));
            Row r2 = sheet.createRow(row++);
            r2.setHeight((short) 564);//行高
            for (int i = 0; i < 18; i++) {
                Cell c = r2.createCell(i);
                if (i == 0) {
                    c.setCellValue("序号");
                }
                if (i == 1) {
                    c.setCellValue("企业名称");
                }
                if (i == 2) {
                    c.setCellValue("统一社会信用代码");
                }
                if (i == 3) {
                    c.setCellValue("行业代码");
                }
                if (i == 4) {
                    c.setCellValue("所在地市");
                }
                if (i == 5) {
                    c.setCellValue(year - 1 + "年综合能源消费量（吨标准煤）");
                }
                if (i == 7) {
                    c.setCellValue(year + "年" + month + "月综合能源消费量（吨标准煤）");
                }
                if (i == 9) {
                    c.setCellValue(year + "年1－" + month + "月综合能源消费量（吨标准煤）");
                }
                if (i == 11) {
                    c.setCellValue(year + "年" + month + "月耗电量（万千瓦时）");
                }
                if (i == 12) {
                    c.setCellValue("主要产品及对应能源消费量");
                }
                c.setCellStyle(style2);
            }
            Row r3 = sheet.createRow(row++);
            r3.setHeight((short) 700);//行高
            for (int i = 0; i < 18; i++) {
                Cell c = r3.createCell(i);
                c.setCellStyle(style2);
                if (i == 5) {
                    c.setCellValue("当量值");
                }
                if (i == 6) {
                    c.setCellValue("等价值");
                }
                if (i == 7) {
                    c.setCellValue("当量值");
                }
                if (i == 8) {
                    c.setCellValue("等价值");
                }
                if (i == 9) {
                    c.setCellValue("当量值");
                }
                if (i == 10) {
                    c.setCellValue("等价值");
                }
                if (i == 12) {
                    c.setCellValue("产品名称");
                }
                if (i == 13) {
                    c.setCellValue("单位");
                }
                if (i == 14) {
                    c.setCellValue("设计产能");
                }
                if (i == 15) {
                    c.setCellValue(year + "年" + month + "月产量");
                }
                if (i == 16) {
                    c.setCellValue(year + "年" + month + "月对应能源消费量（吨标准煤）");
                }
                if (i == 17) {
                    c.setCellValue("备注");
                }
            }

            /* 表格内内容 */
            for (int i = 0; i < 4; i++) {
                for (int g = 0; g < 12; g++) {
                    sheet.addMergedRegion(new CellRangeAddress(row, row + 1, g, g));
                }
                for (int j = 0; j < 2; j++) {
                    Row rf = sheet.createRow(row++);
                    rf.setHeight((short) 564);//行高
                    for (int t = 0; t < 18; t++) {
                        Cell c = rf.createCell(t);
                        c.setCellStyle(style2);
                        if (row == 5) {
                            if (t == 0) {
                                c.setCellValue(1);
                            }
                            if (t == 12) {
                                c.setCellValue("产品1");
                            }
                        }
                        if (row == 6) {
                            if (t == 12) {
                                c.setCellValue("产品2");
                            }
                        }
                        if (row == 7) {
                            if (t == 0) {
                                c.setCellValue(2);
                            }
                        }
                        if (row == 9) {
                            if (t == 0) {
                                c.setCellValue(3);
                            }
                        }
                    }
                }
            }

            /* 总计 */
//            Row rzj = sheet.createRow(row++);
//            rzj.setHeight((short) 564);//行高
//            for (int i = 0; i < 17; i++) {
//                Cell c = rzj.createCell(i);
//                c.setCellStyle(style2);
//                if (i == 1) {
//                    c.setCellValue("总计");
//                }
//            }

            /* 填报内容 */
            Row rtb = sheet.createRow(row++);
            rtb.setHeight((short) 1220);//行高
            for (int i = 0; i < 18; i++) {
                Cell c = rtb.createCell(i);
                c.setCellStyle(style1);
                if (i == 0) {
                    String tbnr = "填报内容：\n" +
                            "1.请填报2021年综合能源消费量50万吨标准煤（当量值）以上或2022年单月综合能源消费量达到5万吨标准煤（当量值）以上的重点企业用能情况；\n" +
                            "2.行业代码按《国民经济行业分类》（GB／T4754－2017）填写；\n" +
                            "3.请视产品情况调整或注明设计产能、产量的单位，如：千瓦时、重量箱等；\n" +
                            "4.如果企业名称不填写，将不会被系统识别；\n";
                    c.setCellValue(tbnr);
                }
            }
            sheet.addMergedRegion(new CellRangeAddress(row - 1, row - 1, 0, 17));
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xls");
            wb.write(response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }
    }


    /**
     * 用能企业导出
     *
     * @param ifExport
     * @param fileName
     * @param datalist
     * @param request
     * @param response
     * @throws Exception
     */
    public static void useEngergyExcel(boolean ifExport, String fileName, List<UseEngergy> datalist, HttpServletRequest request, HttpServletResponse response, String scYear, String scMonth, String region) throws Exception {
        HSSFWorkbook wb = null;
        try {
            wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("sheet1");
            // 字体
            // 附件二字体
            Font headerFont0 = wb.createFont();
            headerFont0.setFontName("方正黑体_GBK");
            headerFont0.setFontHeightInPoints((short) 12);
            headerFont0.setColor(HSSFColor.BLACK.index);
            // XX州（市）重点企业用能情况表字体
            Font headerFont1 = wb.createFont();
            headerFont1.setFontName("方正小标宋_GBK");
            headerFont1.setFontHeightInPoints((short) 20);
            headerFont1.setColor(HSSFColor.BLACK.index);
            // 填报情况字体
            Font font3 = wb.createFont();
            font3.setFontName("方正仿宋_GBK");
            font3.setFontHeightInPoints((short) 10);
            // 表头字体
            Font font4 = wb.createFont();
            font4.setFontName("方正黑体_GBK");
            font4.setFontHeightInPoints((short) 9);

            // 单元格样式
            // 附件二样式
            CellStyle headerStyle0 = wb.createCellStyle();
            headerStyle0.setFont(headerFont0);
            headerStyle0.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            // XX州（市）重点企业用能情况表样式
            CellStyle headerStyle1 = wb.createCellStyle();
            headerStyle1.setFont(headerFont1);
            headerStyle1.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            headerStyle1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            headerStyle1.setLocked(true);
            headerStyle1.setWrapText(false);// 自动换行
            // 填报情况样式
            CellStyle style1 = wb.createCellStyle();
            style1.setFont(font3);
            style1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style1.setWrapText(true);// 自动换行
            style1.setBorderBottom(BorderStyle.THIN); //下边框
            style1.setBorderLeft(BorderStyle.THIN);//左边框
            style1.setBorderTop(BorderStyle.THIN);//上边框
            style1.setBorderRight(BorderStyle.THIN);//右边框
            // 表内文字样式
            CellStyle style2 = wb.createCellStyle();
            style2.setFont(font4);
            style2.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            style2.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style2.setBorderBottom(BorderStyle.THIN); //下边框
            style2.setBorderLeft(BorderStyle.THIN);//左边框
            style2.setBorderTop(BorderStyle.THIN);//上边框
            style2.setBorderRight(BorderStyle.THIN);//右边框
            style2.setWrapText(true);// 自动换行

            int row = 0;
            // 设置列宽
            for (int i = 0; i < 17; i++) {
                if (i == 0) {
                    sheet.setColumnWidth(i, 1000);
                } else {
                    sheet.setColumnWidth(i, 2900);
                }
            }
            //第一行
            Row r0 = sheet.createRow(row++);
            r0.setHeight((short) 462);//行高
            //第一行第一列
            Cell c00 = r0.createCell(0);
            c00.setCellValue("附件二");
            c00.setCellStyle(headerStyle0);
            //合并单元格（从左到右依次：要合并的初始行位置、结束行位置，初始列位置、结束列位置）
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));

            //第2行
            Row r1 = sheet.createRow(row++);
            r1.setHeight((short) 768);//行高
            //第2行第一列
            Cell c10 = r1.createCell(0);
            String title = "";
            if(scYear != null){
                title = region + ("云南".equals(region) ? "省" : "州（市）") + "重点企业用能情况表";
            }else{
                title = "XX州（市）重点企业用能情况表";
                scYear = "2022";
                scMonth = "X";
            }
            c10.setCellValue(title);
            c10.setCellStyle(headerStyle1);
            //合并单元格（从左到右依次：要合并的初始行位置、结束行位置，初始列位置、结束列位置）
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 16));
            //第3、4行
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 0));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 1, 1));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 2, 2));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 3, 3));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 4, 4));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 5, 6));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 7, 8));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 9, 10));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 11, 11));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 12, 16));
            Row r2 = sheet.createRow(row++);
            r2.setHeight((short) 564);//行高
            for (int i = 0; i < 18; i++) {
                Cell c = r2.createCell(i);
                if (i == 0) c.setCellValue("序号");
                if (i == 1) c.setCellValue("企业名称");
                if (i == 2) c.setCellValue("统一社会信用代码");
                if (i == 3) c.setCellValue("行业代码");
                if (i == 4) c.setCellValue("所在地市");
                if (i == 5) c.setCellValue((Integer.parseInt(scYear)-1)+"年综合能源消费量（吨标准煤）");
                if (i == 7) c.setCellValue(scYear+"年"+scMonth+"月综合能源消费量（吨标准煤）");
                if (i == 9) c.setCellValue(scYear+"年1－"+scMonth+"月综合能源消费量（吨标准煤）");
                if (i == 11) c.setCellValue(scYear+"年"+scMonth+"月耗电量（万千瓦时）");
                if (i == 12) c.setCellValue("主要产品及对应能源消费量");
                c.setCellStyle(style2);
            }
            Row r3 = sheet.createRow(row++);
            r3.setHeight((short) 700);//行高
            for (int i = 0; i < 18; i++) {
                Cell c = r3.createCell(i);
                c.setCellStyle(style2);
                if (i == 5) c.setCellValue("当量值");
                if (i == 6) c.setCellValue("等价值");
                if (i == 7) c.setCellValue("当量值");
                if (i == 8) c.setCellValue("等价值");
                if (i == 9) c.setCellValue("当量值");
                if (i == 10) c.setCellValue("等价值");
                if (i == 12) c.setCellValue("产品名称");
                if (i == 13) c.setCellValue("单位");
                if (i == 14) c.setCellValue("设计产能（吨）");
                if (i == 15) c.setCellValue(scYear+"年"+scMonth+"月产量（吨）");
                if (i == 16) c.setCellValue(scYear+"年"+scMonth+"月对应能源消费量（吨标准煤）");
                if (i == 17) c.setCellValue("备注");
            }

            /* 表格内容 */
            if (ifExport) {
                Iterator<UseEngergy> it = datalist.iterator();
                int index = 1;
                while (it.hasNext()) {
                    UseEngergy t = it.next();
                    List<ZstbProduce> produces = t.getProduceList();
                    int produceSize = 1;
                    if (produces != null) {
                        produceSize = produces.size() == 0 ? 1 : produces.size();
                    }
                    // 先合并单元格
                    if (produceSize != 1) {
                        for (int i = 0; i < 12; i++) {
                            sheet.addMergedRegion(new CellRangeAddress(row, row + produceSize - 1, i, i));
                        }
                    }
                    // 循环产品数量的行数
                    for (int i = 0; i < produceSize; i++) {
                        Row r = sheet.createRow(row++);
                        r.setHeight((short) 564);
                        if (i == 0) {
                            for (int j = 0; j < 12; j++) {
                                Cell c = r.createCell(j);
                                c.setCellStyle(style2);
                                if (j == 0) {
                                    c.setCellValue(index++);
                                    continue;
                                }
                                String fieldName = engergyFields[j - 1];
                                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                                Method getMethod = t.getClass().getMethod(getMethodName, new Class[]{});
                                Object value = getMethod.invoke(t, new Object[]{});
                                // 判断值的类型后进行强制类型转换
                                String textValue = null;
                                if (value != null) {
                                    if (value instanceof Integer) {
                                        c.setCellValue((Integer) value);
                                    } else if (value instanceof Float) {
                                        c.setCellValue(new HSSFRichTextString(String.valueOf((Float) value)));
                                    } else if (value instanceof Double) {
                                        c.setCellValue(new HSSFRichTextString(String.valueOf((Double) value)));
                                    } else if (value instanceof Long) {
                                        c.setCellValue((Long) value);
                                    } else if (value instanceof Date) {
                                        Date date = (Date) value;
                                        SimpleDateFormat sdf = new SimpleDateFormat(patten);
                                        textValue = sdf.format(date);
                                    } else {
                                        // 其它数据类型都当作字符串简单处理
                                        textValue = value.toString();
                                    }
                                } else {
                                    textValue = "";
                                }
                                // 利用正则表达式判断textValue是否全部由数字组成
                                if (!org.apache.commons.lang3.StringUtils.isBlank(textValue)) {
                                    Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                                    Matcher matcher = p.matcher(textValue);
                                    if (matcher.matches()) {
                                        // 是数字当作double处理
                                        c.setCellValue(Double.parseDouble(textValue));
                                    } else {
                                        c.setCellValue(new HSSFRichTextString(textValue));
                                    }
                                }
                            }
                        } else {
                            for (int j = 0; j < 12; j++) {
                                Cell c = r.createCell(j);
                                c.setCellStyle(style2);
                            }
                        }
                        // 循环填充产品数据
                        if (produces == null || produces.size() == 0) {
                            for (int j = 12; j < 18; j++) {
                                Cell c = r.createCell(j);
                                c.setCellStyle(style2);
                            }
                        } else {
                            ZstbProduce zi = produces.get(i);
                            for (int j = 12; j < 18; j++) {
                                Cell c = r.createCell(j);
                                c.setCellStyle(style2);
                                String fieldName = produceFields[j - 12];
                                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                                Method getMethod = zi.getClass().getMethod(getMethodName, new Class[]{});
                                Object value = getMethod.invoke(zi, new Object[]{});
                                // 判断值的类型后进行强制类型转换
                                String textValue = null;
                                if (value != null) {
                                    if (value instanceof Integer) {
                                        c.setCellValue((Integer) value);
                                    } else if (value instanceof Float) {
                                        c.setCellValue(new HSSFRichTextString(String.valueOf((Float) value)));
                                    } else if (value instanceof Double) {
                                        c.setCellValue(new HSSFRichTextString(String.valueOf((Double) value)));
                                    } else if (value instanceof Long) {
                                        c.setCellValue((Long) value);
                                    } else if (value instanceof Date) {
                                        Date date = (Date) value;
                                        SimpleDateFormat sdf = new SimpleDateFormat(patten);
                                        textValue = sdf.format(date);
                                    } else {
                                        // 其它数据类型都当作字符串简单处理
                                        textValue = value.toString();
                                    }
                                } else {
                                    textValue = "";
                                }
                                // 利用正则表达式判断textValue是否全部由数字组成
                                if (!org.apache.commons.lang3.StringUtils.isBlank(textValue)) {
                                    Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                                    Matcher matcher = p.matcher(textValue);
                                    if (matcher.matches()) {
                                        // 是数字当作double处理
                                        c.setCellValue(Double.parseDouble(textValue));
                                    } else {
                                        c.setCellValue(new HSSFRichTextString(textValue));
                                    }
                                }
                            }
                        }
                    }
                }
                /* 总计 */
            } else {
                /* 表格内内容 */
                for (int i = 0; i < 4; i++) {
                    for (int g = 0; g < 12; g++) {
                        sheet.addMergedRegion(new CellRangeAddress(row, row + 1, g, g));
                    }
                    for (int j = 0; j < 2; j++) {
                        Row rf = sheet.createRow(row++);
                        rf.setHeight((short) 564);//行高
                        for (int t = 0; t < 18; t++) {
                            Cell c = rf.createCell(t);
                            c.setCellStyle(style2);
                            if (row == 5) {
                                if (t == 0) c.setCellValue(1);
                                if (t == 12) c.setCellValue("产品1");
                            }
                            if (row == 6) {
                                if (t == 12) c.setCellValue("产品2");
                            }
                            if (row == 7) {
                                if (t == 0) c.setCellValue(2);
                            }
                            if (row == 9) {
                                if (t == 0) c.setCellValue(3);
                            }
                        }
                    }
                }
                /* 总计 */
                Row rzj = sheet.createRow(row++);
                rzj.setHeight((short) 564);//行高
                for (int i = 0; i < 18; i++) {
                    Cell c = rzj.createCell(i);
                    c.setCellStyle(style2);
                    if (i == 1) {
                        c.setCellValue("总计");
                    }
                }
            }


            /* 填报内容 */
            Row rtb = sheet.createRow(row++);
            rtb.setHeight((short) 1220);//行高
            for (int i = 0; i < 18; i++) {
                Cell c = rtb.createCell(i);
                c.setCellStyle(style1);
                if (i == 0) {
                    String tbnr = "填报内容：\n" +
                            "1.请填报2021年综合能源消费量50万吨标准煤（当量值）以上或2022年单月综合能源消费量达到5万吨标准煤（当量值）以上的重点企业用能情况；\n" +
                            "2.行业代码按《国民经济行业分类》（GB／T4754－2017）填写；\n" +
                            "3.请视产品情况调整或注明设计产能、产量的单位，如：千瓦时、重量箱等；\n" +
                            "4.如果企业名称不填写，将不会被系统识别；\n";
                    c.setCellValue(tbnr);
                }
            }
            sheet.addMergedRegion(new CellRangeAddress(row - 1, row - 1, 0, 16));
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xls");
            wb.write(response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }
    }


    /*
     * 新增固定资产投资项目节能审查实施情况报送信息表 模板
     * */
    public static void infoTemplate(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        HSSFWorkbook wb = null;
        try {
            wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("sheet1");
            // 字体
            // 附件2字体
            Font headerFont0 = wb.createFont();
            headerFont0.setFontName("方正黑体_GBK");
            headerFont0.setFontHeightInPoints((short) 12);
            headerFont0.setColor(HSSFColor.BLACK.index);
            // XX州、市新增固定资产投资项目节能审查实施情况报送信息表（2021年X月） 字体
            Font headerFont1 = wb.createFont();
            headerFont1.setFontName("方正小标宋简体");
            headerFont1.setFontHeightInPoints((short) 16);
            headerFont1.setColor(HSSFColor.BLACK.index);
            // 填报情况字体
            Font font3 = wb.createFont();
            font3.setFontName("方正仿宋_GBK");
            font3.setFontHeightInPoints((short) 10);
            // 表头字体
            Font font4 = wb.createFont();
            font4.setFontName("方正黑体_GBK");
            font4.setFontHeightInPoints((short) 12);
            // 表内字体
            Font font5 = wb.createFont();
            font5.setFontName("Times New Roman");
            font5.setFontHeightInPoints((short) 10);

            // 单元格样式
            // 附件二样式
            CellStyle headerStyle0 = wb.createCellStyle();
            headerStyle0.setFont(headerFont0);
            headerStyle0.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            headerStyle0.setAlignment(HorizontalAlignment.CENTER);// 左右居中

            // XX州（市）重点企业用能情况表样式
            CellStyle headerStyle1 = wb.createCellStyle();
            headerStyle1.setFont(headerFont1);
            headerStyle1.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            headerStyle1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            headerStyle1.setLocked(true);
            headerStyle1.setWrapText(false);// 自动换行
            // 填报情况样式
            CellStyle style1 = wb.createCellStyle();
            style1.setFont(font3);
            style1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style1.setWrapText(true);// 自动换行

            // 表头文字样式
            CellStyle style2 = wb.createCellStyle();
            style2.setFont(font4);
            style2.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            style2.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style2.setBorderBottom(BorderStyle.THIN); //下边框
            style2.setBorderLeft(BorderStyle.THIN);//左边框
            style2.setBorderTop(BorderStyle.THIN);//上边框
            style2.setBorderRight(BorderStyle.THIN);//右边框
            style2.setWrapText(true);// 自动换行
            // 表内文字样式
            CellStyle style3 = wb.createCellStyle();
            style3.setFont(font5);
            style3.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            style3.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style3.setBorderBottom(BorderStyle.THIN); //下边框
            style3.setBorderLeft(BorderStyle.THIN);//左边框
            style3.setBorderTop(BorderStyle.THIN);//上边框
            style3.setBorderRight(BorderStyle.THIN);//右边框
            style3.setWrapText(true);// 自动换行

            int row = 0;
            // 设置列宽
            for (int i = 0; i < 19; i++) {
                if (i == 0) {
                    sheet.setColumnWidth(i, 2000);
                } else {
                    sheet.setColumnWidth(i, 3300);
                }
            }

            //第一行
            Row r0 = sheet.createRow(row++);
            r0.setHeight((short) 312);//行高  20 = 1磅
            Cell c00 = r0.createCell(0);
            c00.setCellValue("附件2");
            c00.setCellStyle(headerStyle0);
            //第二行
            Row r1 = sheet.createRow(row++);
            r1.setHeight((short) 600);//行高  20 = 1磅
            Cell c10 = r1.createCell(0);
            c10.setCellValue("XX州、市新增固定资产投资项目节能审查实施情况报送信息表（2021年X月）");
            c10.setCellStyle(headerStyle1);
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 18));

            // 第三行
            Row r2 = sheet.createRow(row++);
            r2.setHeight((short) 312);
            for (int i = 0; i < 19; i++) {
                Cell c = r2.createCell(i);
                c.setCellStyle(headerStyle0);
                if (i == 0) {
                    c.setCellValue("单位（盖章）：");
                }
                if (i == 11) {
                    c.setCellValue("联系人：");
                }
                if (i == 13) {
                    c.setCellValue("联系电话（手机号）：");
                }
            }
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 1));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 2, 10));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 13, 15));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 16, 18));

            // 表头 4、5 行
            for (int i = 0; i < 19; i++) {
                if (i == 13 || i == 14) {
                    continue;
                }
                sheet.addMergedRegion(new CellRangeAddress(3, 4, i, i));
            }
            sheet.addMergedRegion(new CellRangeAddress(3, 3, 13, 14));
            // 表头第一行
            String[] header3 = {"序号", "项目名称", "项目代码", "建设单位", "所在州市", "行业代码", "行业类别",
                    "“两高”行业代码", "开工时间", "拟投产时间", "节能审查机关", "审查完成时间", "审查意见文号",
                    "年综合能源消费量（吨标准煤）", "节能效果（吨标准煤）", "电力消耗量（万千瓦时)",
                    "煤炭消费量（吨标准煤）", "备注"};

            Row r3 = sheet.createRow(row++);
            r3.setHeight((short) 800);//行高  20 = 1磅
            for (int i = 0; i < 19; i++) {
                Cell c = r3.createCell(i);
                c.setCellStyle(style2);
                if (i == 14) {
                    continue;
                }
                if (i > 14) {
                    c.setCellValue(header3[i - 1]);
                } else {
                    c.setCellValue(header3[i]);
                }
            }
            Row r4 = sheet.createRow(row++);
            r4.setHeight((short) 540);//行高  20 = 1磅
            for (int i = 0; i < 19; i++) {
                Cell c = r4.createCell(i);
                c.setCellStyle(style2);
                if (i == 13) {
                    c.setCellValue("当量值");
                }
                if (i == 14) {
                    c.setCellValue("等价值");
                }
            }

            /* 示例内容 */
            String[] content = {"示例：1", "XXXX新建项目", "2021-350900-41-03-059865", "XXXX有限公司", "", "", "",
                    "", "", "2023年1月1日", "XXXX发改委", "2021年1月1日", "XX发改环资〔2021〕XX号", "", "", "", "", "", ""};
            Row r5 = sheet.createRow(row++);
            r5.setHeight((short) 1020);//行高  20 = 1磅
            for (int i = 0; i < 19; i++) {
                Cell c = r5.createCell(i);
                c.setCellValue(content[i]);
                c.setCellStyle(style3);
            }

            /* 填报说明 */
            Row rtb = sheet.createRow(row++);
            rtb.setHeight((short) 1612);//行高
            Cell crtb0 = rtb.createCell(0);
            crtb0.setCellStyle(style1);
            String tbnr = "填报说明：\n" +
                    "1.请填报年综合能源消费量1000吨标准煤以上的项目节能审查实施情况；\n" +
                    "2.行业类别、行业代码分别按《国民经济行业分类》（GB／T4754－2017）中类别名称、代码类别填写；\n" +
                    "3.“两高”行业代码选择六大行业中对应行业代码：25-石油、煤炭及其他燃料加工业，26-化学原料和化学制品制造业，30-非金属矿物制品业，31-黑色金属冶炼和压延加工业，32-有色金属冶炼和压延加工业， 44-电力、热力生产和供应业。";
            crtb0.setCellValue(tbnr);
            sheet.addMergedRegion(new CellRangeAddress(row - 1, row - 1, 0, 18));
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xls");
            wb.write(response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }

    }

    /**
     * 新增固定资产投资项目节能审查实施情况报送信息表 导出
     *
     * @param ifExport 是否是导出 true 导出， false 导出模板
     * @param datalist 导出的数据集，导出模板用不到
     * @param fileName 导出的Excel名称
     */
    public static void infoExcel(boolean ifExport, List<ZstbInfo> datalist, String fileName, HttpServletRequest request, HttpServletResponse response, String[] capacityAvi, String scYear, String scMonth, String region) throws Exception {
        HSSFWorkbook wb = null;
        try {
            wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("sheet1");
            // 字体
            // 附件2字体
            Font headerFont0 = wb.createFont();
            headerFont0.setFontName("方正黑体_GBK");
            headerFont0.setFontHeightInPoints((short) 12);
            headerFont0.setColor(HSSFColor.BLACK.index);
            // XX州、市新增固定资产投资项目节能审查实施情况报送信息表（2021年X月） 字体
            Font headerFont1 = wb.createFont();
            headerFont1.setFontName("方正小标宋简体");
            headerFont1.setFontHeightInPoints((short) 16);
            headerFont1.setColor(HSSFColor.BLACK.index);
            // 填报情况字体
            Font font3 = wb.createFont();
            font3.setFontName("方正仿宋_GBK");
            font3.setFontHeightInPoints((short) 10);
            // 表头字体
            Font font4 = wb.createFont();
            font4.setFontName("方正黑体_GBK");
            font4.setFontHeightInPoints((short) 12);
            // 表内字体
            Font font5 = wb.createFont();
            font5.setFontName("Times New Roman");
            font5.setFontHeightInPoints((short) 10);

            // 单元格样式
            // 附件二样式
            CellStyle headerStyle0 = wb.createCellStyle();
            headerStyle0.setFont(headerFont0);
            headerStyle0.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            headerStyle0.setAlignment(HorizontalAlignment.CENTER);// 左右居中

            // XX州（市）重点企业用能情况表样式
            CellStyle headerStyle1 = wb.createCellStyle();
            headerStyle1.setFont(headerFont1);
            headerStyle1.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            headerStyle1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            headerStyle1.setLocked(true);
            headerStyle1.setWrapText(false);// 自动换行
            // 填报情况样式
            CellStyle style1 = wb.createCellStyle();
            style1.setFont(font3);
            style1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style1.setWrapText(true);// 自动换行

            // 表头文字样式
            CellStyle style2 = wb.createCellStyle();
            style2.setFont(font4);
            style2.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            style2.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style2.setBorderBottom(BorderStyle.THIN); //下边框
            style2.setBorderLeft(BorderStyle.THIN);//左边框
            style2.setBorderTop(BorderStyle.THIN);//上边框
            style2.setBorderRight(BorderStyle.THIN);//右边框
            style2.setWrapText(true);// 自动换行
//            style2.setFillForegroundColor(IndexedColors.YELLOW.getIndex());

            // 表头文字样式
            CellStyle style2Color = wb.createCellStyle();
            style2Color.setFont(font4);
            style2Color.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            style2Color.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style2Color.setBorderBottom(BorderStyle.THIN); //下边框
            style2Color.setBorderLeft(BorderStyle.THIN);//左边框
            style2Color.setBorderTop(BorderStyle.THIN);//上边框
            style2Color.setBorderRight(BorderStyle.THIN);//右边框
            style2Color.setWrapText(true);// 自动换行
            style2Color.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            style2Color.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            // 表内文字样式
            CellStyle style3 = wb.createCellStyle();
            style3.setFont(font5);
            style3.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            style3.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style3.setBorderBottom(BorderStyle.THIN); //下边框
            style3.setBorderLeft(BorderStyle.THIN);//左边框
            style3.setBorderTop(BorderStyle.THIN);//上边框
            style3.setBorderRight(BorderStyle.THIN);//右边框
            style3.setWrapText(true);// 自动换行

            //需要被设置为下拉数据的单元格范围
//            CellRangeAddressList capacityList = new CellRangeAddressList(3, 5000, 4, 4);
            CellRangeAddressList capacityList = new CellRangeAddressList(3, 5000, 5, 5);

            // 设置辅修下拉框数据
            DataValidationHelper helper = sheet.getDataValidationHelper();
            DataValidationConstraint capacityConstraint = helper.createExplicitListConstraint(capacityAvi);
            DataValidation capacityDataValidation = helper.createValidation(capacityConstraint, capacityList);
            sheet.addValidationData(capacityDataValidation);

            int row = 0;
            // 设置列宽
//            for (int i = 0; i < 20; i++) {
            for (int i = 0; i < 28; i++) {
                if (i == 0) {
                    sheet.setColumnWidth(i, 2000);
                } else {
                    sheet.setColumnWidth(i, 3300);
                }
            }

            //第一行
            Row r0 = sheet.createRow(row++);
            r0.setHeight((short) 312);//行高  20 = 1磅
            Cell c00 = r0.createCell(0);
            c00.setCellValue("附件2");
            c00.setCellStyle(headerStyle0);
            //第二行
            Row r1 = sheet.createRow(row++);
            r1.setHeight((short) 600);//行高  20 = 1磅
            Cell c10 = r1.createCell(0);
//            String title = "";
//            if( scYear != null){
//                title = title = region + ("云南".equals(region) ? "省" : "州（市）") + "固定资产投资项目节能审查实施情况报送信息表（"+scYear+"年"+scMonth+"月）";
//            }else{
//                title = "XX州（市）固定资产投资项目节能审查实施情况报送信息表（2021年X月）";
//            }
            String title = "全省固定资产投资项目节能审查情况表";
            c10.setCellValue(title);
            c10.setCellStyle(headerStyle1);
//            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 20));
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 27));


            // 第三行
            Row r2 = sheet.createRow(row++);
            r2.setHeight((short) 312);
//            for (int i = 0; i < 21; i++) {
            for (int i = 0; i < 28; i++) {
                Cell c = r2.createCell(i);
                c.setCellStyle(headerStyle0);
                if (i == 0) {
                    c.setCellValue("单位（盖章）：");
                }
//                if (i == 11) {1925
                if (i == 16) {
                    c.setCellValue("联系人：");
                }
//                if (i == 15) {
                if (i == 19) {
                    c.setCellValue("联系电话（手机号）：");
                }
                if (i == 25) {
                    c.setCellValue("填报日期：");
                }
            }
//            sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 1));
//            sheet.addMergedRegion(new CellRangeAddress(2, 2, 2, 10));
//            sheet.addMergedRegion(new CellRangeAddress(2, 2, 11, 12));
//            sheet.addMergedRegion(new CellRangeAddress(2, 2, 13, 14));
//            sheet.addMergedRegion(new CellRangeAddress(2, 2, 15, 17));
//            sheet.addMergedRegion(new CellRangeAddress(2, 2, 18, 20));

            sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 1));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 2, 15));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 17, 18));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 19, 22));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 23, 24));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 25, 27));

            // 表头 4、5 行
//            for (int i = 0; i < 21; i++) {
//                if (i == 15 || i == 16) {
            for (int i = 0; i < 28; i++) {
                if (i == 19 || i == 20) {
                    continue;
                }
                sheet.addMergedRegion(new CellRangeAddress(3, 4, i, i));
            }
//            sheet.addMergedRegion(new CellRangeAddress(3, 3, 15, 16));
            sheet.addMergedRegion(new CellRangeAddress(3, 3, 19, 20));

            // 表头第一行
//            String[] header3 = {"序号", "项目名称", "项目代码", "建设单位", "所在州市", "行业代码", "行业类别",
//                    "“两高”行业代码", "开工时间", "拟投产时间", "节能审查机关", "审查完成时间", "审查意见文号",
//                    "投资金额（万元）","工业总产值（万元）","年综合能源消费量（吨标准煤）", "节能效果（吨标准煤）",
//                    "电力消耗量（万千瓦时)","煤炭消费量（吨标准煤）", "备注"};
            String[] header3 = {"序号", "项目名称", "项目性质", "项目代码", "建设单位", "所在州县（市、区）", "行业代码", "行业类别",
                    "“两高”行业代码", "建设内容", "主要产品", "是否已开工（是/否）", "项目进度", "建设起止时间", "拟投产时间", "节能审查机关", "审查意见批复时间",
                    "审查意见文号", "项目总投资（万元）", "年综合能源消费量（吨标准煤）", "原料用能消费量（吨标准煤）","单位工业增加值能耗（吨标准煤/万元）",
                    "设计用电负荷（万kW）", "年设计用电量（万kWh）", "度电产值（元/kWh）", "煤炭消费量（吨标准煤）", "备注"};

            Row r3 = sheet.createRow(row++);
            r3.setHeight((short) 800);//行高  20 = 1磅
//            for (int i = 0; i < 21; i++) {
            for (int i = 0; i < 28; i++) {
                Cell c = r3.createCell(i);
                //判断导出数据还是导出模板
                if (ifExport) {
                    c.setCellStyle(style2);
                } else {
                    if (i == 8 || i == 27) {
                        c.setCellStyle(style2);
                    } else {
                        c.setCellStyle(style2Color);
                    }
                }

//                if (i == 16) {
                if (i == 20) {
                    continue;
                }
//                if (i > 16) {
                if (i > 20) {
                    c.setCellValue(header3[i - 1]);
                } else {
                    c.setCellValue(header3[i]);
                }
            }
            Row r4 = sheet.createRow(row++);
            r4.setHeight((short) 540);//行高  20 = 1磅
//            for (int i = 0; i < 21; i++) {
            for (int i = 0; i < 28; i++) {
                Cell c = r4.createCell(i);
                if (ifExport) {
                    c.setCellStyle(style2);
                } else {
                    c.setCellStyle(style2Color);
                }
//                if (i == 15) {
                if (i == 19) {
                    c.setCellValue("当量值");
                }
//                if (i == 16) {
                if (i == 20) {
                    c.setCellValue("等价值");
                }
            }
            if (ifExport) {
                Iterator<ZstbInfo> it = datalist.iterator();
                int index = 1;
                while (it.hasNext()) {
                    Row r = sheet.createRow(row++);
                    r.setHeight((short) 1020);//行高  20 = 1磅
                    ZstbInfo t = it.next();
//                    for (int i = 0; i < 21; i++) {
                    for (int i = 0; i < 28; i++) {
                        Cell c = r.createCell(i);
                        c.setCellStyle(style3);
                        if (i == 0) {
                            c.setCellValue(index++);
                            continue;
                        }
                        String fieldName = infoFields[i - 1];
                        String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                        Method getMethod = t.getClass().getMethod(getMethodName, new Class[]{});
                        Object value = getMethod.invoke(t, new Object[]{});
                        // 判断值的类型后进行强制类型转换
                        String textValue = null;
                        if (value != null) {
                            if (value instanceof Integer) {
                                c.setCellValue((Integer) value);
                            } else if (value instanceof Float) {
                                c.setCellValue(new HSSFRichTextString(String.valueOf((Float) value)));
                            } else if (value instanceof Double) {
                                c.setCellValue(new HSSFRichTextString(String.valueOf((Double) value)));
                            } else if (value instanceof Long) {
                                c.setCellValue((Long) value);
                            } else if (value instanceof Date) {
                                Date date = (Date) value;
                                SimpleDateFormat sdf = new SimpleDateFormat(patten);
                                textValue = sdf.format(date);
                            } else {
                                // 其它数据类型都当作字符串简单处理
                                textValue = value.toString();
                            }
                        } else {
                            textValue = "";
                        }
                        // 利用正则表达式判断textValue是否全部由数字组成
                        if (!org.apache.commons.lang3.StringUtils.isBlank(textValue)) {
                            Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                            Matcher matcher = p.matcher(textValue);
                            if (matcher.matches()) {
                                // 是数字当作double处理
                                c.setCellValue(Double.parseDouble(textValue));
                            } else {
                                c.setCellValue(new HSSFRichTextString(textValue));
                            }
                        }
                    }
                }
            } else {
                /* 示例内容 */
//                String[] content = {"示例：1", "XXXX新建项目", "", "2021-350900-41-03-059865", "XXXX有限公司", "", "", "",
//                        "", "", "2023年1月1日", "XXXX发改委", "2021年1月1日", "XX发改环资〔2021〕XX号", "", "", "", "", "", "", "", ""};
                String[] content = {"示例：1", "XXXX新建项目", "", "2021-350900-41-03-059865", "XXXX有限公司", "州县（市、区）", "", "",
                        "", "建设内容", "产品1", "是/否", "项目进度", "XXXX年XX月XX日 到 XXXX年XX月XX日", "拟投产时间", "节能审查机关", "XXXX年XX月XX日", "审查意见文号",
                        "", "", "", "","",
                        "", "", "", "", "示例"};
                Row r5 = sheet.createRow(row++);
                r5.setHeight((short) 1020);//行高  20 = 1磅
//                for (int i = 0; i < 21; i++) {
                for (int i = 0; i < 28; i++) {
                    Cell c = r5.createCell(i);
                    c.setCellValue(content[i]);
                    c.setCellStyle(style3);
                }
            }

            /* 填报说明 */
            Row rtb = sheet.createRow(row++);
            rtb.setHeight((short) 1612);//行高
            Cell crtb0 = rtb.createCell(0);
            crtb0.setCellStyle(style1);
            String tbnr = "填报说明：\n" +
                    "1.请填报年综合能源消费量1000吨标准煤以上的项目节能审查实施情况；\n" +
                    "2.行业类别、行业代码分别按《国民经济行业分类》（GB／T4754－2017）中类别名称、代码类别填写；\n" +
                    "3.“两高”行业代码选择六大行业中对应行业代码：25-石油、煤炭及其他燃料加工业，26-化学原料和化学制品制造业，30-非金属矿物制品业，31-黑色金属冶炼和压延加工业，32-有色金属冶炼和压延加工业， 44-电力、热力生产和供应业。";
            crtb0.setCellValue(tbnr);
//            sheet.addMergedRegion(new CellRangeAddress(row - 1, row - 1, 0, 20));
            sheet.addMergedRegion(new CellRangeAddress(row - 1, row - 1, 0, 27));

            if (!ifExport) {

                CellStyle styleWarn = wb.createCellStyle();
                styleWarn.setFont(font3);
                styleWarn.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
                styleWarn.setWrapText(true);// 自动换行
                styleWarn.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
                styleWarn.setFillPattern(FillPatternType.SOLID_FOREGROUND);

                Row warn = sheet.createRow(row++);
                sheet.addMergedRegion(new CellRangeAddress(row - 1, row - 1, 0, 3));
                warn.setHeight((short) 540);//行高
                Cell warn0 = warn.createCell(0);
                warn0.setCellStyle(styleWarn);
                String warnStr = "注：表头黄色标出内容为必填项";
                warn0.setCellValue(warnStr);

            }

        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xls");
            wb.write(response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }
    }

    public static void infoSaveByExcel() {

    }

    /**
     * zstb_info excel数据导入  转成list
     *
     * @param file
     */
    public static List<ZstbInfo> infoToList(MultipartFile file, String date) throws Exception {
        List<ZstbInfo> list = new ArrayList<>();
        int fristRowNum = 0, i = 0;
        try {
            Sheet sheet = null;
            if(file.getOriginalFilename().endsWith("xls")) {
                HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
                sheet = workbook.getSheetAt(0);
            } else if(file.getOriginalFilename().endsWith("xlsx")) {
                XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
                sheet = workbook.getSheetAt(0);
            }
            fristRowNum = 5;  // 从第6行开始读数据，索引为5
            int lastRowNum = sheet.getLastRowNum();   // 最后一行减1行为结束行
            while (fristRowNum < lastRowNum) {
                Row row = sheet.getRow(fristRowNum);
                if(isEmptyRow(row)){ //空行
                    fristRowNum++;
                    continue;
                }
                Map<String, Object> t = new HashMap<>();
                for ( i = 0; i < infoFields.length; i++) {
                    String fieldName = infoFields[i];
                    Cell cell = row.getCell(i + 1);
                    if(CellType.FORMULA.equals(cell.getCellTypeEnum())){
                        ZstbInfo info = new ZstbInfo();
                        info.setName("导入失败，第" + (fristRowNum + 1) + "行" + infoFieldsName[i] + "为计算公式，请填写正确内容！");
                        List<ZstbInfo> zstbInfos = new ArrayList<>();
                        zstbInfos.add(info);
                        return zstbInfos;
                    }

                    if(!StringUtils.isEmpty(cell)){
                        if (fieldName.equals("startDate") || fieldName.equals("produceDate") || fieldName.equals("checkFinishDate")){
//                            if (row.getCell(i + 1).toString().contains("年")){
//                                String string = row.getCell(i + 1).toString();
//                                String replace = string.replace("年", "-").replace("月", "-").replace("日", "-");
//                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//                                Date parse = format.parse(replace);
//                                t.put(fieldName, format.format(parse));
//                            }else {
//                                double cellValue = row.getCell(i + 1).getNumericCellValue();
////                                String cellValue = row.getCell(i + 1).getStringCellValue();
//                                Date javaDate = HSSFDateUtil.getJavaDate(cellValue);
//                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//                                t.put(fieldName,format.format(javaDate));
//                                t.put(fieldName,cellValue);
//                            }

//                            if (row.getCell(i + 1).toString().contains("年")){
//                                String string = row.getCell(i + 1).toString();
//                                String replace = string.replace("年", "-").replace("月", "-").replace("日", "-");
//                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//                                Date parse = format.parse(replace);
//                                t.put(fieldName, format.format(parse));
//                            }else if (row.getCell(i + 1).toString().contains("-")){
//                                String string = row.getCell(i + 1).toString();
//                                t.put(fieldName, string);
//                            }else {
//                                double cellValue = Double.parseDouble(row.getCell(i + 1).toString());
//                                Date javaDate = HSSFDateUtil.getJavaDate(cellValue);
//                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//                                t.put(fieldName,format.format(javaDate));
//                            }
                            String cellValue = getDateValue(cell);
                            t.put(fieldName, cellValue);
                        }else {
                            cell.setCellType(CellType.STRING);
                            t.put(fieldName, cell.toString());
                        }

                        //    确定必填项
                        if ((cell.toString().equals("") || cell.toString() == null) && i != 7  && i != 26) {
//                        if ((cell(i + 1).toString().equals("") || cell(i + 1).toString() == null)) {
                            ZstbInfo info = new ZstbInfo();
                            info.setName("导入失败，第" + (fristRowNum + 1) + "行" + infoFieldsName[i] + "必填");
                            List<ZstbInfo> sb = new ArrayList<>();
                            sb.add(info);
                            return sb;
                        }
                    }
                }
                if(t!=null && t.size()>0){
                    ZstbInfo zstbInfo = JSON.parseObject(JSON.toJSONString(t), ZstbInfo.class);
                    ScUser u = SecurityUtils.getUser();
                    zstbInfo.setDeptId(u.getDeptId().toString());
                    zstbInfo.setDelFlag("1");
                    zstbInfo.setAddTime(new Date());
                    zstbInfo.setScYear(date.split("-")[0]);
                    zstbInfo.setScMonth(date.split("-")[1]);
                    zstbInfo.setIndustryCode(zstbInfo.getIndustryCode().replace(".0","")); //行业编码去除最后的 .0
                    list.add(zstbInfo);
                }
                fristRowNum++;
            }
        } catch (IOException e) {
            //throw e;
            ZstbInfo info = new ZstbInfo();
            info.setName("导入失败，第" + (fristRowNum + 1) + "行" + infoFieldsName[i] + "出现错误，原因为" + e.getMessage());
            List<ZstbInfo> zstbInfos = new ArrayList<>();
            zstbInfos.add(info);
            return zstbInfos;
        }
        return list;
    }

    public static List<UseEngergy> useExcelToList(MultipartFile file, String datel) throws Exception {
        int year = Integer.parseInt(datel.split("-")[0]);
        int month = Integer.parseInt(datel.split("-")[1]);
        String[] engergyName = {
                "企业名称", "统一社会信用代码", "行业代码", "所在地市", "年综合能源消费量当量值", "年综合能源消费量等价值",
                year - 1 + "年" + month + "月综合能源消费量当量值", year + "年" + month + "月综合能源消费量等价值", year + "年1－" + month + "月综合能源消费量当量值", year + "年1－" + month + "月综合能源消费量等价值", year + "年" + month + "月耗电量（万千瓦时）"
        };
        String[] produceName =
                {"产品名称", "单位", "设计产能（吨）", year + "年" + month + "月产量（吨）", year + "年" + month + "月对应能源消费量（吨标准煤）", "备注"};
        List<UseEngergy> list = new ArrayList<>();  // 主表集合
        List<ZstbProduce> ps = new ArrayList<>();  // 副表集合
        UseEngergy useEngergy = null;  // 主表对象
        try {
            Sheet sheet = null;
            if(file.getOriginalFilename().endsWith("xls")) {
                HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
                sheet = workbook.getSheetAt(0);
            } else if(file.getOriginalFilename().endsWith("xlsx")) {
                XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
                sheet = workbook.getSheetAt(0);
            }
            int fristRowNum = 4;  // 从第5行开始读数据，索引为4
            int lastRowNum = sheet.getLastRowNum();   // 最后一行减 2 行为结束行
            while (fristRowNum <= lastRowNum) {
                Row row = sheet.getRow(fristRowNum);
                Map<String, Object> t = new HashMap<>();
                Map<String, Object> p = new HashMap<>();
                // 先循环列  一共17个单元格， 0-11 主表  12-16 副表
                // 主表
                if (fristRowNum == lastRowNum) {
                    useEngergy.setProduceList(ps);
                    list.add(useEngergy);
                    break;
                }
                if(isEmptyRow(row)){ //空行
                    fristRowNum++;
                    continue;
                }
                if (!row.getCell(1).toString().equals("") && row.getCell(1) != null) { // 判断是不是起始行
                    // 组装数据
                    if (useEngergy != null) {
                        useEngergy.setProduceList(ps);
                        list.add(useEngergy);
                    }
                    // 清空
                    ps = new ArrayList<>();
                    useEngergy = new UseEngergy();

                    for (int i = 0; i < 11; i++) {
                        String fieldName = engergyFields[i];
                        t.put(fieldName, row.getCell(i + 1).toString());
                        if (row.getCell(i + 1).toString() == "" || row.getCell(i + 1).toString() == null) {
                            useEngergy.setEnterpriseName("导入失败，第" + (fristRowNum + 1) + "行" + engergyName[i] + "必填");
                            List<UseEngergy> sb = new ArrayList<>();
                            sb.add(useEngergy);
                            return sb;
                        }
                    }
                    useEngergy = JSON.parseObject(JSON.toJSONString(t), UseEngergy.class);
                }

                if (!row.getCell(12).toString().equals("") && row.getCell(12) != null) { // 判断产品是否为空
                    // 副表
                    for (int i = 12; i < 18; i++) {
                        String fieldName = produceFields[i - 12];
                        p.put(fieldName, row.getCell(i).toString());
//                    if ((row.getCell(i).toString() == "" || row.getCell(i).toString() == null) && i == 12) {
//                        useEngergy.setEnterpriseName("导入失败，第" + (fristRowNum + 1) + "行" + produceName[i - 12] + "必填");
//                        List<UseEngergy> sb = new ArrayList<>();
//                        sb.add(useEngergy);
//                        return sb;
//                    }
                    }
                    ZstbProduce zp = JSON.parseObject(JSON.toJSONString(p), ZstbProduce.class);
                    ps.add(zp);
                }
                fristRowNum++;
            }
        } catch (IOException e) {
            throw e;
        }

        return list;
    }

    /**
     * 两高月报模板导出
     *
     * @param
     * @param request
     * @param response
     * @param capacityAvi
     */
    public static void StockMonth(String fileName, HttpServletRequest request, HttpServletResponse response, String[] capacityAvi) throws Exception {
        HSSFWorkbook wb = null;
        try {
            wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("sheet1");
            // 字体
            // 附件二字体
            Font headerFont0 = wb.createFont();
            headerFont0.setFontName("方正黑体_GBK");
            headerFont0.setFontHeightInPoints((short) 12);
            headerFont0.setColor(HSSFColor.BLACK.index);
            // XX州（市）重点企业用能情况表字体
            Font headerFont1 = wb.createFont();
            headerFont1.setFontName("方正小标宋_GBK");
            headerFont1.setFontHeightInPoints((short) 20);
            headerFont1.setColor(HSSFColor.BLACK.index);
            // 填报情况字体
            Font font3 = wb.createFont();
            font3.setFontName("方正仿宋_GBK");
            font3.setFontHeightInPoints((short) 10);
            // 表头字体
            Font font4 = wb.createFont();
            font4.setFontName("方正黑体_GBK");
            font4.setFontHeightInPoints((short) 9);

            // 单元格样式
            // 附件二样式
            CellStyle headerStyle0 = wb.createCellStyle();
            headerStyle0.setFont(headerFont0);
            headerStyle0.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            // XX州（市）重点企业用能情况表样式
            CellStyle headerStyle1 = wb.createCellStyle();
            headerStyle1.setFont(headerFont1);
            headerStyle1.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            headerStyle1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            headerStyle1.setLocked(true);
            headerStyle1.setWrapText(false);// 自动换行
            // 填报情况样式
            CellStyle style1 = wb.createCellStyle();
            style1.setFont(font3);
            style1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style1.setWrapText(true);// 自动换行
            style1.setBorderBottom(BorderStyle.THIN); //下边框
            style1.setBorderLeft(BorderStyle.THIN);//左边框
            style1.setBorderTop(BorderStyle.THIN);//上边框
            style1.setBorderRight(BorderStyle.THIN);//右边框
            // 表内文字样式
            CellStyle style2 = wb.createCellStyle();
            style2.setFont(font4);
            style2.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            style2.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style2.setBorderBottom(BorderStyle.THIN); //下边框
            style2.setBorderLeft(BorderStyle.THIN);//左边框
            style2.setBorderTop(BorderStyle.THIN);//上边框
            style2.setBorderRight(BorderStyle.THIN);//右边框
            style2.setWrapText(true);// 自动换行


//            String[] capacityAvi = {"昆明,530100","五华区,530111"};
            //需要被设置为下拉数据的单元格范围
            CellRangeAddressList capacityList = new CellRangeAddressList(3, 5000, 4, 4);
            // 设置辅修下拉框数据
            DataValidationHelper helper = sheet.getDataValidationHelper();
            DataValidationConstraint capacityConstraint = helper.createExplicitListConstraint(capacityAvi);
            DataValidation capacityDataValidation = helper.createValidation(capacityConstraint, capacityList);
            sheet.addValidationData(capacityDataValidation);


            int row = 0;
            // 设置列宽
            for (int i = 0; i < 17; i++) {
                if (i == 0) {
                    sheet.setColumnWidth(i, 1000);
                } else {
                    sheet.setColumnWidth(i, 2900);
                }
            }
            //第一行
            Row r0 = sheet.createRow(row++);
            r0.setHeight((short) 462);//行高
            //第一行第一列
            Cell c00 = r0.createCell(0);
            c00.setCellValue("附件1-1");
            c00.setCellStyle(headerStyle0);
            //合并单元格（从左到右依次：要合并的初始行位置、结束行位置，初始列位置、结束列位置）
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));

            //第2行
            Row r1 = sheet.createRow(row++);
            r1.setHeight((short) 768);//行高
            //第2行第一列
            Cell c10 = r1.createCell(0);
            c10.setCellValue("云南省存量“两高”企业清单（5000tce以上）");
            c10.setCellStyle(headerStyle1);
            //合并单元格（从左到右依次：要合并的初始行位置、结束行位置，初始列位置、结束列位置）
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 16));
            //第3、4行
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 0));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 1, 1));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 2, 2));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 3, 3));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 4, 4));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 5, 6));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 7, 8));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 9, 10));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 11, 11));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 12, 16));
            Row r2 = sheet.createRow(row++);
            r2.setHeight((short) 564);//行高
            for (int i = 0; i < 17; i++) {
                Cell c = r2.createCell(i);
                if (i == 0) {
                    c.setCellValue("序号");
                }
                if (i == 1) {
                    c.setCellValue("组织机构代码");
                }
                if (i == 2) {
                    c.setCellValue("企业名称");
                }
                if (i == 3) {
                    c.setCellValue("所在州市");
                }
                if (i == 4) {
                    c.setCellValue("行业类别");
                }
                if (i == 5) {
                    c.setCellValue("“两高”行业代码");
                }
                if (i == 7) {
                    c.setCellValue("行业代码");
                }
                if (i == 9) {
                    c.setCellValue("企业运行状态（正常生产/停产）");
                }
                if (i == 11) {
                    c.setCellValue("2021年X月耗电量（万千瓦时）");
                }
                if (i == 12) {
                    c.setCellValue("主要产品及对应能源消费量");
                }
                c.setCellStyle(style2);
            }
            Row r3 = sheet.createRow(row++);
            r3.setHeight((short) 700);//行高
            for (int i = 0; i < 17; i++) {
                Cell c = r3.createCell(i);
                c.setCellStyle(style2);
                if (i == 5) {
                    c.setCellValue("当量值");
                }
                if (i == 6) {
                    c.setCellValue("等价值");
                }
                if (i == 7) {
                    c.setCellValue("当量值");
                }
                if (i == 8) {
                    c.setCellValue("等价值");
                }
                if (i == 9) {
                    c.setCellValue("当量值");
                }
                if (i == 10) {
                    c.setCellValue("等价值");
                }
                if (i == 12) {
                    c.setCellValue("产品名称");
                }
                if (i == 13) {
                    c.setCellValue("设计产能（吨）");
                }
                if (i == 14) {
                    c.setCellValue("2022年X月产量（吨）");
                }
                if (i == 15) {
                    c.setCellValue("2022年X月对应能源消费量（吨标准煤）");
                }
                if (i == 16) {
                    c.setCellValue("备注");
                }
            }

            /* 表格内内容 */
            for (int i = 0; i < 4; i++) {
                for (int g = 0; g < 12; g++) {
                    sheet.addMergedRegion(new CellRangeAddress(row, row + 1, g, g));
                }
                for (int j = 0; j < 2; j++) {
                    Row rf = sheet.createRow(row++);
                    rf.setHeight((short) 564);//行高
                    for (int t = 0; t < 17; t++) {
                        Cell c = rf.createCell(t);
                        c.setCellStyle(style2);
                        if (row == 5) {
                            if (t == 0) {
                                c.setCellValue(1);
                            }
                            if (t == 12) {
                                c.setCellValue("产品1");
                            }
                        }
                        if (row == 6) {
                            if (t == 12) {
                                c.setCellValue("产品2");
                            }
                        }
                        if (row == 7) {
                            if (t == 0) {
                                c.setCellValue(2);
                            }
                        }
                        if (row == 9) {
                            if (t == 0) {
                                c.setCellValue(3);
                            }
                        }
                    }
                }
            }

//            /* 总计 */
//            Row rzj = sheet.createRow(row++);
//            rzj.setHeight((short) 564);//行高
//            for (int i = 0; i < 17; i++) {
//                Cell c = rzj.createCell(i);
//                c.setCellStyle(style2);
//                if (i == 1) {
//                    c.setCellValue("总计");
//                }
//            }

            /* 填报内容 */
            Row rtb = sheet.createRow(row++);
            rtb.setHeight((short) 1220);//行高
            for (int i = 0; i < 17; i++) {
                Cell c = rtb.createCell(i);
                c.setCellStyle(style1);
                if (i == 0) {
                    String tbnr = "填报内容：\n" +
                            "1.请填报2021年综合能源消费量50万吨标准煤（当量值）以上或2022年单月综合能源消费量达到5万吨标准煤（当量值）以上的重点企业用能情况；\n" +
                            "2.行业代码按《国民经济行业分类》（GB／T4754－2017）填写；\n" +
                            "3.请视产品情况调整或注明设计产能、产量的单位，如：千瓦时、重量箱等；\n" +
                            "4.如果企业名称不填写，将不会被系统识别；\n";
                    c.setCellValue(tbnr);
                }
            }
            sheet.addMergedRegion(new CellRangeAddress(row - 1, row - 1, 0, 16));
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xls");
            wb.write(response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }

    }

    /**
     * 两高导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static List<DischargeEnergyStockMonth> StockExcelToList(MultipartFile file, String type) throws IOException, ParseException {
        List<DischargeEnergyStockMonth> list = new ArrayList<>();
        List<DischargeEnergyProductMonth> product = new ArrayList<>();
        DischargeEnergyStockMonth dischargeEnergyStockMonth = null;
        int fristRowNum = 0, i = 0;

        try {
            Sheet sheet = null;
            if(file.getOriginalFilename().endsWith("xls")) {
                HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
                sheet = workbook.getSheetAt(0);
            } else if(file.getOriginalFilename().endsWith("xlsx")) {
                XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
                sheet = workbook.getSheetAt(0);
            }
            int lastRowNum = sheet.getLastRowNum();   // 最后一行减1行为结束行
            if ("1".equals(type)) {
                //存量
                fristRowNum = 6;
                while (fristRowNum <= lastRowNum) {
                    Row row = sheet.getRow(fristRowNum);
                    Map<String, Object> t = new HashMap<>();
                    Map<String, Object> p = new HashMap<>();
                    // 先循环列  一共18个单元格， 0-11 主表  12-17 副表
                    // 主表
                    if (fristRowNum == lastRowNum) {
                        dischargeEnergyStockMonth.setProduceList(product);
                        list.add(dischargeEnergyStockMonth);
                        break;
                    }

                    if(isEmptyRow(row)){ //空行
                        fristRowNum++;
                        continue;
                    }
                    String warn = row.getCell(0)==null?"":row.getCell(0).toString();
                    if (warn.contains("说明") || warn.contains("注")) {
                        //fristRowNum++;
                        fristRowNum = lastRowNum; //避免说明或注意事项后面还有空白行
                        continue;
                    }
//                    if(!StringUtils.isEmpty(row.getCell(1))){

                    String last = row.getCell(1)==null?"":row.getCell(1).toString();
                    if (!last.equals("")) { // 判断是不是起始行
                        // 组装数据
                        if (dischargeEnergyStockMonth != null) {
                            dischargeEnergyStockMonth.setProduceList(product);
                            list.add(dischargeEnergyStockMonth);
                        }
                        // 清空
                        product = new ArrayList<>();
                        dischargeEnergyStockMonth = new DischargeEnergyStockMonth();
                        for ( i = 0; i < stockFieldsCl.length; i++) {
                            String fieldName = stockFieldsCl[i];
                            int index = i + 1; //模板中有序号字段，不导入系统；模板字段下标比系统字段下标多1
                            String itemValue = "";
                            Cell cell = row.getCell(index);

                            //判断单元格内容是否为空
                            ArrayList<Integer> noRequired = new ArrayList<>();
                            Collections.addAll(noRequired,20, 21, 33, 43);
                            itemValue = cell ==null?"": cell.toString();
                            if (org.apache.commons.lang3.StringUtils.isEmpty(itemValue) && !noRequired.contains(index)) {
                                if(index != 24){ //水泥设计产能可以为空
                                    dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameCl[i] + "必填");
                                    List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                    sb.add(dischargeEnergyStockMonth);
                                    return sb;
                                } else {
                                    //水泥设计产能可以为空
                                    String productName = row.getCell(16).toString();
                                    if (!productName.contains("水泥")) {
                                        dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameCl[i] + "必填");
                                        List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                        sb.add(dischargeEnergyStockMonth);
                                        return sb;
                                    }
                                }
                            }


                            if (fieldName.equals("energyTime")){
                                itemValue = getDateValue(cell);
                                t.put(fieldName, itemValue);
                            }else {
                                //row.getCell(index).setCellType(CellType.STRING);
                                itemValue = cell ==null?"": cell.toString();  //项目值
                                t.put(fieldName, itemValue);
                            }
                            //i取值 2项目名称 7节能审查机关 8审查完成时间 9节能审查批复文号 12若是，原料用能 15设计产能 16~20预计实际产量 22/24年综合能源消费量等价值 25备注
//                            ArrayList<Integer> noRequired = new ArrayList<>();
//                            Collections.addAll(noRequired,2,7,8,9,12,16,17,18,19,20,22,24,25);
//                            if (org.apache.commons.lang3.StringUtils.isEmpty(itemValue) && !noRequired.contains(i)) {
//                            if (org.apache.commons.lang3.StringUtils.isEmpty(itemValue)) {
//                                if(i!=15 || (i==15 && !itemValue.contains("水泥")) ){ //水泥设计产能可以为空
//                                    dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameCl[i] + "必填");
//                                    List<DischargeEnergyStockMonth> sb = new ArrayList<>();
//                                    sb.add(dischargeEnergyStockMonth);
//                                    return sb;
//                                }
//                            }
                        }
                        dischargeEnergyStockMonth = JSON.parseObject(JSON.toJSONString(t), DischargeEnergyStockMonth.class);
                    }
                    // 产品副表
                    for ( i = 0; i < stockFieldsCl.length; i++) {
                        int index = i + 1;
//                        if (index < 8 || index == 12 || index == 13 || index == 21 || index == 22 || index == 23 || index == 24 || index == 25) {
//                        } else {
                        String fieldName = stockFieldsCl[i];
                        //row.getCell(index).setCellType(CellType.STRING);
                        String value = row.getCell(index)==null?"":row.getCell(index).toString();

                        //副表
                        ArrayList<Integer> secondaryTable = new ArrayList<>();
                        //Collections.addAll(secondaryTable,16,17,18,19,20,21,24,25,26,27,28,33,42);
                        Collections.addAll(secondaryTable,16,17,18,19,20,21,42);
                        if (secondaryTable.contains(index)) {
                            ArrayList<Integer> noRequired = new ArrayList<>();
                            Collections.addAll(noRequired, 20, 21, 33, 43);
                            if (org.apache.commons.lang3.StringUtils.isEmpty(value) && !noRequired.contains(index)) {
                                if (index != 24) { //水泥设计产能可以为空
                                    dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameCl[i] + "必填");
                                    List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                    sb.add(dischargeEnergyStockMonth);
                                    return sb;
                                } else {
                                    //水泥设计产能可以为空
                                    String productName = row.getCell(16).toString();
                                    if (!productName.contains("水泥")) {
                                        dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameCl[i] + "必填");
                                        List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                        sb.add(dischargeEnergyStockMonth);
                                        return sb;
                                    }
                                }
                            }
                        }

                        p.put(fieldName, value);
                        //i取值 15设计产能
//                        if ((value.equals("") || value == null) && i==15) {
////                            String value1 = row.getCell(i-1)==null?"":row.getCell(i-1).toString();
//                            //需排除表格填写说明
//                            if(!StringUtils.isEmpty(value) && !value.contains("水泥")){ //产品名称非空 且 产品名称不包含水泥，其设计产能不可以为空
//                                dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameCl[i] + "必填");
//                                List<DischargeEnergyStockMonth> sb = new ArrayList<>();
//                                sb.add(dischargeEnergyStockMonth);
//                                return sb;
//                            }
//                        }
//                        }
                    }
                    DischargeEnergyProductMonth zp = JSON.parseObject(JSON.toJSONString(p), DischargeEnergyProductMonth.class);
                    product.add(zp);
                    fristRowNum++;
                }
            } else if ("2".equals(type)) {
                //在建
                fristRowNum = 5;
                while (fristRowNum <= lastRowNum) {
                    Row row = sheet.getRow(fristRowNum);
                    Map<String, Object> t = new HashMap<>();
                    Map<String, Object> p = new HashMap<>();
                    // 先循环列  一共17个单元格， 0-11 主表  12-16 副表
                    // 主表
                    if (fristRowNum == lastRowNum) {
                        dischargeEnergyStockMonth.setProduceList(product);
                        list.add(dischargeEnergyStockMonth);
                        break;
                    }

                    if(isEmptyRow(row)){ //空行
                        fristRowNum++;
                        continue;
                    }
                    String warn = row.getCell(0)==null?"":row.getCell(0).toString();
                    if (warn.contains("说明") || warn.contains("注")) {
                        //fristRowNum++;
                        fristRowNum = lastRowNum; //避免说明或注意事项后面还有空白行
                        continue;
                    }
//                    String s = row.getCell(1).toString();
                    if (!row.getCell(1).toString().equals("") && row.getCell(1) != null) { // 判断是不是起始行
                        // 组装数据
                        if (dischargeEnergyStockMonth != null) {
                            dischargeEnergyStockMonth.setProduceList(product);
                            list.add(dischargeEnergyStockMonth);
                        }
                        // 清空
                        product = new ArrayList<>();
                        dischargeEnergyStockMonth = new DischargeEnergyStockMonth();
                        for ( i = 0; i < stockFieldsZj.length; i++) {
                            String fieldName = stockFieldsZj[i];
                            int index = i + 1; //模板中有序号字段，不导入系统；模板字段下标比系统字段下标多1
                            String itemValue = null;
                            Cell cell = row.getCell(index);

                            //判断单元格内容是否为空
                            ArrayList<Integer> noRequired = new ArrayList<>();
                            Collections.addAll(noRequired,17, 18, 19, 30, 35);
                            itemValue = cell ==null?"": cell.toString();
                            if (org.apache.commons.lang3.StringUtils.isEmpty(itemValue) && !noRequired.contains(index)) {
                                if(index != 21){ //水泥设计产能可以为空
                                    dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameZj[i] + "必填");
                                    List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                    sb.add(dischargeEnergyStockMonth);
                                    return sb;
                                } else {
                                    //水泥设计产能可以为空
                                    String productName = row.getCell(20).toString();
                                    if (!productName.contains("水泥")) {
                                        dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameZj[i] + "必填");
                                        List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                        sb.add(dischargeEnergyStockMonth);
                                        return sb;
                                    }
                                }
                            }

                            if (fieldName.equals("energyTime") || fieldName.equals("startTime") || fieldName.equals("productionTime")){
                                //关闭时间字段校验与转换
                                itemValue = getDateValue(cell);
                                t.put(fieldName, itemValue);
                            }else {
                                //row.getCell(index).setCellType(CellType.STRING);
                                itemValue = cell ==null?"": cell.toString();  //项目值
                                t.put(fieldName, itemValue);
                            }
//                            String itemValue = row.getCell(index)==null?"":row.getCell(index).toString();  //项目值
//                            t.put(fieldName, itemValue);
                            //i取值 6节能审查机关 7审查完成时间 8节能审查批复文号 14若是，原料用能 17设计产能 18~21预计产能 26节能效果  23/25能耗等价值  29备注
//                            ArrayList<Integer> noRequired = new ArrayList<>();
//                            Collections.addAll(noRequired,6,7,8,14,18,19,20,21,23,25,26,29);
//                            if (org.apache.commons.lang3.StringUtils.isEmpty(itemValue) && !noRequired.contains(i)) {
//                                if(i!=17 || (i==17 && !itemValue.contains("水泥")) ){ //水泥设计产能可以为空
//                                    dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameZj[i] + "必填");
//                                    List<DischargeEnergyStockMonth> sb = new ArrayList<>();
//                                    sb.add(dischargeEnergyStockMonth);
//                                    return sb;
//                                }
//                            }
                        }
                        dischargeEnergyStockMonth = JSON.parseObject(JSON.toJSONString(t), DischargeEnergyStockMonth.class);
                    }
                    // 副表
                    for ( i = 0; i < stockFieldsZj.length; i++) {
                        int index = i + 1;
//                        if (index == 7 || index == 8 || index == 9 || index == 10 || index == 16 || index == 17 || index == 18 || index == 19 || index == 20 || index == 21) {
                        String fieldName = stockFieldsZj[i];
                        //row.getCell(index).setCellType(CellType.STRING);
                        String value = row.getCell(index)==null?"":row.getCell(index).toString();

                        ArrayList<Integer> secondaryTable = new ArrayList<>();
                        //Collections.addAll(secondaryTable,2,3,4,20,21,26,30,31,35);
                        Collections.addAll(secondaryTable,20,21);
                        if (secondaryTable.contains(index)) {
                            ArrayList<Integer> noRequired = new ArrayList<>();
                            Collections.addAll(noRequired,17, 18, 19, 30, 35);
                            if (org.apache.commons.lang3.StringUtils.isEmpty(value ) && !noRequired.contains(index)) {
                                if(i != 21){ //水泥设计产能可以为空
                                    dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameZj[i] + "必填");
                                    List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                    sb.add(dischargeEnergyStockMonth);
                                    return sb;
                                } else {
                                    //水泥设计产能可以为空
                                    String productName = row.getCell(20).toString();
                                    if (!productName.contains("水泥")) {
                                        dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameZj[i] + "必填");
                                        List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                        sb.add(dischargeEnergyStockMonth);
                                        return sb;
                                    }
                                }
                            }
                        }


                        p.put(fieldName, value);
                        //i取值 17设计产能
//                        if (value.equals("") && i == 17) {
//                            //需排除表格填写说明
//                            if(!StringUtils.isEmpty(value) && !value.contains("水泥")){ //产品名称非空 且 产品名称不包含水泥，其设计产能不可以为空
//                                dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameZj[i] + "必填");
//                                List<DischargeEnergyStockMonth> sb = new ArrayList<>();
//                                sb.add(dischargeEnergyStockMonth);
//                                return sb;
//                            }
//                        }
//                        }
                    }
                    DischargeEnergyProductMonth zp = JSON.parseObject(JSON.toJSONString(p), DischargeEnergyProductMonth.class);
                    product.add(zp);
                    fristRowNum++;
                }

            } else if ("3".equals(type)) {
                //拟建
                fristRowNum = 5;
                while (fristRowNum <= lastRowNum) {
                    Row row = sheet.getRow(fristRowNum);
                    Map<String, Object> t = new HashMap<>();
                    Map<String, Object> p = new HashMap<>();
                    // 先循环列  一共17个单元格， 0-11 主表  12-16 副表
                    // 主表
                    if (fristRowNum == lastRowNum) {
                        dischargeEnergyStockMonth.setProduceList(product);
                        list.add(dischargeEnergyStockMonth);
                        break;
                    }

                    if(isEmptyRow(row)){ //空行
                        fristRowNum++;
                        continue;
                    }
                    String warn = row.getCell(0)==null?"":row.getCell(0).toString();
                    if (warn.contains("说明") || warn.contains("注")) {
                        //fristRowNum++;
                        fristRowNum = lastRowNum; //避免说明或注意事项后面还有空白行
                        continue;
                    }

                    if (!row.getCell(1).toString().equals("") && row.getCell(1) != null) { // 判断是不是起始行
                        // 组装数据
                        if (dischargeEnergyStockMonth != null) {
                            dischargeEnergyStockMonth.setProduceList(product);
                            list.add(dischargeEnergyStockMonth);
                        }
                        // 清空
                        product = new ArrayList<>();
                        dischargeEnergyStockMonth = new DischargeEnergyStockMonth();
                        for ( i = 0; i < stockFieldsNj.length; i++) {
                            String fieldName = stockFieldsNj[i];
                            int index = i + 1; //模板中有序号字段，不导入系统；模板字段下标比系统字段下标多1
                            String itemValue = null;
                            Cell cell = row.getCell(index);

                            //判断单元格内容是否为空
                            ArrayList<Integer> noRequired = new ArrayList<>();
                            Collections.addAll(noRequired,16, 17, 27, 33);
                            itemValue = cell ==null?"": cell.toString();
                            if (org.apache.commons.lang3.StringUtils.isEmpty(itemValue) && !noRequired.contains(index)) {
                                if(index != 19){ //水泥设计产能可以为空
                                    dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameNj[i] + "必填");
                                    List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                    sb.add(dischargeEnergyStockMonth);
                                    return sb;
                                } else {
                                    //水泥设计产能可以为空
                                    String productName = row.getCell(18).toString();
                                    if (!productName.contains("水泥")) {
                                        dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameNj[i] + "必填");
                                        List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                        sb.add(dischargeEnergyStockMonth);
                                        return sb;
                                    }
                                }
                            }

                            if (fieldName.equals("energyTime") || fieldName.equals("startTime") || fieldName.equals("productionTime")){
                                itemValue = getDateValue(cell);
                                t.put(fieldName, itemValue);
                            }else {
                                //row.getCell(index).setCellType(CellType.STRING);
                                itemValue = cell ==null?"": cell.toString();  //项目值
                                t.put(fieldName, itemValue);
                            }
//                            String itemValue = row.getCell(index)==null?"":row.getCell(index).toString();  //项目值
//                            t.put(fieldName, itemValue);
                            //i取值 6节能审查机关 7审查完成时间 8节能审查批复文号 14若是，原料用能 17设计产能 18~21预计产能 26节能效果  23/25能耗等价值  29备注
//                            ArrayList<Integer> noRequired = new ArrayList<>();
//                            Collections.addAll(noRequired,6,7,8,14,18,19,20,21,23,25,26,29);
//                            if (org.apache.commons.lang3.StringUtils.isEmpty(itemValue) && !noRequired.contains(i)) {
//                                if(i!=17 || (i==17 && !itemValue.contains("水泥")) ){ //水泥设计产能可以为空
//                                    dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameNj[i] + "必填");
//                                    List<DischargeEnergyStockMonth> sb = new ArrayList<>();
//                                    sb.add(dischargeEnergyStockMonth);
//                                    return sb;
//                                }
//                            }
                        }
                        dischargeEnergyStockMonth = JSON.parseObject(JSON.toJSONString(t), DischargeEnergyStockMonth.class);
                    }
                    // 副表
                    for ( i = 0; i < stockFieldsNj.length; i++) {
                        int index = i + 1;
//                        if (index == 7 || index == 8 || index == 9 || index == 10 || index == 16 || index == 17 || index == 18 || index == 19 || index == 20 || index == 21) {
                        String fieldName = stockFieldsNj[i];
                        //row.getCell(index).setCellType(CellType.STRING);
                        String value = row.getCell(index)==null?"":row.getCell(index).toString();

                        ArrayList<Integer> secondaryTable = new ArrayList<>();
                        //Collections.addAll(secondaryTable,2,3,4,18,19,24,27,28,33);
                        Collections.addAll(secondaryTable,18,19);
                        if (secondaryTable.contains(index)) {
                            ArrayList<Integer> noRequired = new ArrayList<>();
                            Collections.addAll(noRequired,16, 17, 27, 33);
                            if (org.apache.commons.lang3.StringUtils.isEmpty(value) && !noRequired.contains(index)) {
                                if(index != 19){ //水泥设计产能可以为空
                                    dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameNj[i] + "必填");
                                    List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                    sb.add(dischargeEnergyStockMonth);
                                    return sb;
                                } else {
                                    //水泥设计产能可以为空
                                    String productName = row.getCell(18).toString();
                                    if (!productName.contains("水泥")) {
                                        dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameNj[i] + "必填");
                                        List<DischargeEnergyStockMonth> sb = new ArrayList<>();
                                        sb.add(dischargeEnergyStockMonth);
                                        return sb;
                                    }
                                }
                            }
                        }


                        p.put(fieldName, value);
                        //i取值 17设计产能
//                        if (value.equals("") && i == 17) {
//                            //需排除表格填写说明
//                            if(!StringUtils.isEmpty(value) && !value.contains("水泥")){ //产品名称非空 且 产品名称不包含水泥，其设计产能不可以为空
//                                dischargeEnergyStockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + stockFieldsNameNj[i] + "必填");
//                                List<DischargeEnergyStockMonth> sb = new ArrayList<>();
//                                sb.add(dischargeEnergyStockMonth);
//                                return sb;
//                            }
//                        }
//                        }
                    }
                    DischargeEnergyProductMonth zp = JSON.parseObject(JSON.toJSONString(p), DischargeEnergyProductMonth.class);
                    product.add(zp);
                    fristRowNum++;
                }

            }

        } catch (IOException e) {
            //throw e;
            DischargeEnergyStockMonth stockMonth = new DischargeEnergyStockMonth();
            String cellName = "";
            if("1".equals(type)){
                cellName = stockFieldsNameCl[i];
            }else if("2".equals(type)){
                cellName = stockFieldsNameZj[i];
            }else{
                cellName = stockFieldsNameNj[i];
            }
            stockMonth.setItemName("导入失败，第" + (fristRowNum + 1) + "行" + cellName + "出现错误，原因为" + e.getMessage());
            List<DischargeEnergyStockMonth> stockMonths = new ArrayList<>();
            stockMonths.add(stockMonth);
            return stockMonths;
        }
        return list;
    }

    public static void StockExcel(HttpServletResponse response, List<DischargeEnergyStockMonth> list, String type) throws Exception {
        try {
            HSSFWorkbook wb = null;
            wb = new HSSFWorkbook();
            Sheet sheet = wb.createSheet("sheet1");
            // 字体
            // 附件1-1
            Font headerFont0 = wb.createFont();
            headerFont0.setFontName("方正黑体_GBK");
            headerFont0.setFontHeightInPoints((short) 12);
            headerFont0.setColor(HSSFColor.BLACK.index);
            // 云南省存量“两高”企业清单（5000tce以上）
            Font headerFont1 = wb.createFont();
            headerFont1.setFontName("方正小标宋_GBK");
            headerFont1.setFontHeightInPoints((short) 20);
            headerFont1.setColor(HSSFColor.BLACK.index);
            // 填报情况字体
            Font font3 = wb.createFont();
            font3.setFontName("方正仿宋_GBK");
            font3.setFontHeightInPoints((short) 10);
            // 表头字体
            Font font4 = wb.createFont();
            font4.setFontName("方正黑体_GBK");
            font4.setFontHeightInPoints((short) 9);
            // 单元格样式
            // 附件二样式
            CellStyle headerStyle0 = wb.createCellStyle();
            headerStyle0.setFont(headerFont0);
            headerStyle0.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            // XX州（市）重点企业用能情况表样式
            CellStyle headerStyle1 = wb.createCellStyle();
            headerStyle1.setFont(headerFont1);
            headerStyle1.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            headerStyle1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            headerStyle1.setLocked(true);
            headerStyle1.setWrapText(false);// 自动换行
            // 填报情况样式
            CellStyle style1 = wb.createCellStyle();
            style1.setFont(font3);
            style1.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style1.setWrapText(true);// 自动换行
            style1.setBorderBottom(BorderStyle.THIN); //下边框
            style1.setBorderLeft(BorderStyle.THIN);//左边框
            style1.setBorderTop(BorderStyle.THIN);//上边框
            style1.setBorderRight(BorderStyle.THIN);//右边框
            // 表内文字样式
            CellStyle style2 = wb.createCellStyle();
            style2.setFont(font4);
            style2.setAlignment(HorizontalAlignment.CENTER);// 左右居中
            style2.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
            style2.setBorderBottom(BorderStyle.THIN); //下边框
            style2.setBorderLeft(BorderStyle.THIN);//左边框
            style2.setBorderTop(BorderStyle.THIN);//上边框
            style2.setBorderRight(BorderStyle.THIN);//右边框
            style2.setWrapText(true);// 自动换行
            int row = 0;
            // 设置列宽
            for (int i = 0; i < 17; i++) {
                if (i == 0) {
                    sheet.setColumnWidth(i, 1000);
                } else {
                    sheet.setColumnWidth(i, 2900);
                }
            }
            //第一行
            Row r0 = sheet.createRow(row++);
            r0.setHeight((short) 462);//行高
            //第一行第一列
            Cell c00 = r0.createCell(0);
            c00.setCellValue("附件二");
            c00.setCellStyle(headerStyle0);
            //合并单元格（从左到右依次：要合并的初始行位置、结束行位置，初始列位置、结束列位置）
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
            //第2行
            Row r1 = sheet.createRow(row++);
            r1.setHeight((short) 768);//行高
            //第2行第一列
            Cell c10 = r1.createCell(0);
            c10.setCellValue("云南省存量“两高”企业清单（5000tce以上）");
            c10.setCellStyle(headerStyle1);
            //合并单元格（从左到右依次：要合并的初始行位置、结束行位置，初始列位置、结束列位置）
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 16));
            //第3、4行
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 0));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 11));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 12, 13));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 14, 24));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 25, 25));
            Row r2 = sheet.createRow(row++);
            r2.setHeight((short) 564);//行高
            for (int i = 0; i < 30; i++) {
                Cell c = r2.createCell(i);
                if (i == 0) c.setCellValue("序号");
                if (i == 1) c.setCellValue("基本信息");
                if (i == 12) c.setCellValue("原料用能消费量");
                if (i == 14) c.setCellValue("主要产品及能源消费量");
                if (i == 25) c.setCellValue("备注");
                c.setCellStyle(style2);
            }
            Row r3 = sheet.createRow(row++);
            r3.setHeight((short) 700);//行高
            for (int i = 0; i < 30; i++) {
                Cell c = r3.createCell(i);
                c.setCellStyle(style2);
                if (i == 1) c.setCellValue("社会信用代码");
                if (i == 2) c.setCellValue("等价值");
                if (i == 7) c.setCellValue("当量值");
                if (i == 8) c.setCellValue("等价值");
                if (i == 9) c.setCellValue("当量值");
                if (i == 10) c.setCellValue("等价值");
                if (i == 12) c.setCellValue("产品名称");
                if (i == 13) c.setCellValue("设计产能（吨）");
                if (i == 14) c.setCellValue("2022年X月产量（吨）");
                if (i == 15) c.setCellValue("2022年X月对应能源消费量（吨标准煤）");
                if (i == 16) c.setCellValue("备注");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 判断该行是否为空
     */
    public static boolean isEmptyRow(Row row){
        //行不存在
        if (row == null) {
            return true;
        }
        //第一个列位置
        int firstCellNum = row.getFirstCellNum();
        //最后一列位置
        int lastCellNum = row.getLastCellNum();
        //空列数量
        int nullCellNum = 0;
        for (int c = firstCellNum; c < lastCellNum; c++) {
            Cell cell = row.getCell(c);
            if (null == cell || CellType.BLANK.equals(cell.getCellType())) {
                nullCellNum ++;
                continue;
            }
            cell.setCellType(CellType.STRING);
            String cellValue = cell.getStringCellValue().trim();
            if (StringUtils.isEmpty(cellValue)) {
                nullCellNum ++;
            }
        }
        //所有列都为空 只有一列有数据
        if (nullCellNum == (lastCellNum - firstCellNum) || nullCellNum == (lastCellNum - firstCellNum - 1)) {
            return true;
        }
        return false;
    }

    /**
     * excel导入 日期格式调整
     */
    public static String getDateValue(Cell cell){
        String cellValue = "", formatDate = "";
        try{
            if(cell.toString().startsWith("20")){ //日期格式以20开头，不用调整
                cellValue = cell.toString();
            }else{
                Double d = Double.parseDouble(cell.toString());
                switch (cell.getCellStyle().getDataFormat()){
                    case 14:
                        formatDate = "yyyy-MM-dd";
                        break;
                    case 20:
                        formatDate = "HH:mm";
                        break;
                    case 21:
                        formatDate = "HH:mm:ss";
                        break;
                    case 31:
                        formatDate = "yyyy年MM月dd日";
                        break;
                    case 32:
                        formatDate = "HH时mm分";
                        break;
                    case 33:
                        formatDate = "HH时mm分mm秒";
                        break;
                    case 57:
                        formatDate = "yyyy年MM月";
                        break;
                    case 58:
                        formatDate = "MM月dd日";
                        break;
                    case 176:
                        formatDate = "yyyy-MM-dd";
                        break;
                    default:
                        formatDate = "yyyy年MM月dd日";
                        break;
                }
                Date dateCellValue = HSSFDateUtil.getJavaDate(d+1); //excel获取的数字转为日期后，与实际日期相差一天，所以+1
                cellValue = DateUtils.formatDate(dateCellValue, formatDate);
            }
        }catch (Exception e){
            cellValue = cell.toString();
        }finally {
            return cellValue;
        }
    }

}
