package com.rf.psychological.utils;

import com.alibaba.fastjson.JSONObject;

import com.rf.psychological.dao.cognizeModel.*;
import com.rf.psychological.dao.model.*;
import com.rf.psychological.file.excel.ExcelBean;
import com.rf.psychological.scale.dao.model.ScaleEntity;
import com.rf.psychological.utils.OSUtil;
import jodd.util.StringUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zzf
 * @description:Excel 导出工具了哦
 * @date 2021/1/27 9:18
 */
public class ExcelUtil {

    /**
     * excel 版本
     **/
    private final static String excel2003L = ".xls";
    private final static String excel2007U = ".xlsx";

    /**
     * Excel导入
     */
    public static List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception {
        List<List<Object>> list = null;
        //创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        System.out.println("work.getNumberOfSheets()：" + work.getNumberOfSheets());
        for (int i = 0; i < work.getNumberOfSheets() - 1; i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            int sheetSize = 0;
            //遍历当前sheet中的所有行
            //包涵头部，所以要小于等于最后一列数,这里也可以在初始值加上头部行数，以便跳过头部
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                //读取一行
                row = sheet.getRow(j);
                //去掉空行和表头
                if (row.getFirstCellNum() == j) {
                    sheetSize = row.getLastCellNum();
                }
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }
                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < sheetSize; y++) {
                    cell = row.getCell(y);
                    li.add(cell != null ? getCellValue(cell) : null);
                }
                list.add(li);
            }
        }
        return list;
    }

    /**
     * Excel分sheet导入
     */
    public static List<List<List<Object>>> getBankListByExcelSheet(InputStream in, String fileName) throws Exception {
        List<List<List<Object>>> list = null;
        //创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        list = new ArrayList<List<List<Object>>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets() - 1; i++) {
            List<List<Object>> sheets = new ArrayList<List<Object>>();
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            int sheetSize = 0;
            //遍历当前sheet中的所有行
            //包涵头部，所以要小于等于最后一列数,这里也可以在初始值加上头部行数，以便跳过头部
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                //读取一行
                row = sheet.getRow(j);
                //去掉空行和表头
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }
                if (isAllRowEmpty(row, sheet.getRow(0))) {
                    continue;
                }
                sheetSize = row.getLastCellNum();
                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < sheetSize; y++) {
                    cell = row.getCell(y);
                    if (cell == null) {
                        continue;
                    }
                    li.add(cell != null ? getCellValue(cell) : null);
                }
                sheets.add(li);
            }
            list.add(sheets);
        }
        return list;
    }

    /**
     * 验证excel是否全部为空
     *
     * @param row      当前行
     * @param firstRow 第一行标题行
     * @return
     */
    public static boolean isAllRowEmpty(Row row, Row firstRow) {
        int count = 0;
        //单元格数量
        int rowCount = firstRow.getLastCellNum() - firstRow.getFirstCellNum();
        //判断多少个单元格为空
        for (int c = 0; c < rowCount; c++) {
            Cell cell = row.getCell(c);
            if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK || StringUtil.isEmpty((cell + "").trim())) {
                count += 1;
            }
        }

        if (count == rowCount) {
            return true;
        }

        return false;
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     */
    private static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            //2003-
            wb = new HSSFWorkbook(inStr);
        } else if (excel2007U.equals(fileType)) {
            //2007+
            wb = new XSSFWorkbook(inStr);
        } else {
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     */
    private static Object getCellValue(Cell cell) {
        Object value = null;
        //格式化字符类型的数字
        DecimalFormat df = new DecimalFormat("0");
        //日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
        //格式化数字
        DecimalFormat df2 = new DecimalFormat("0.00");
        switch (cell.getCellType()) {

            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    value = df.format(cell.getNumericCellValue());
                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf.format(cell.getDateCellValue());
                } else {
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            case Cell.CELL_TYPE_FORMULA: //公式类型
                try {
                    if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                        value = df.format(cell.getNumericCellValue());
                    } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                        value = sdf.format(cell.getDateCellValue());
                    } else {
                        value = df2.format(cell.getNumericCellValue());
                    }
                } catch (IllegalStateException e) {
                    value = String.valueOf(cell.getRichStringCellValue());
                }
                break;
            default:
                break;
        }
        return value;
    }

    /**
     * @param clazz     数据类
     * @param objs      导出数据列表
     * @param resultMap 计算结果，各项得分
     * @param map       表头
     * @param fileName  文件名
     * @param sheetName sheet页命
     * @return
     * @throws Exception
     */
    public static XSSFWorkbook createExcelFile(Class clazz, List objs, List<Map<String, String>> resultMap, Map<Integer, List<ExcelBean>> map, String fileName, String sheetName) throws Exception {
        // 创建新的Excel工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 在Excel工作簿中建一工作表，其名为缺省值, 也可以指定Sheet名称
        XSSFSheet sheet = workbook.createSheet(sheetName);
        // 以下为excel的字体样式以及excel的标题与内容的创建，下面会具体分析;
        //字体样式
        createFont(workbook);
        //创建标题（头）
        createTableHeader(sheet, map);
        //创建内容
        createTableRows(sheet, map, objs, resultMap, clazz);
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        File file = new File("./"+date+"/"+sheetName+"/"+fileName);
//        if(!file.exists()){
////            file.createNewFile();
//            file.mkdirs();
//        }
        FileOutputStream fileOutputStream = null;
        if (OSUtil.isLinux()) {
            File file = new File("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName);
            if (!file.exists()) {
                //file.createNewFile();
                file.mkdirs();
            }
            fileOutputStream = new FileOutputStream("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName + "/" + fileName);
        } else {
            File file = new File("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName);
            if (!file.exists()) {
                //file.createNewFile();
                file.mkdirs();
            }
            fileOutputStream = new FileOutputStream("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName + "/" + fileName);
        }
//        FileOutputStream  fileOutputStream= new FileOutputStream("./"+date+"/"+sheetName+"/"+fileName);
//        FileOutputStream  fileOutputStream= new FileOutputStream(file);
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        return workbook;
    }

    /**
     * @param clazzs      数据类列表
     * @param objs        三个情绪识别题目列表
     * @param resultJson  三个情绪识别的答案
     * @param tableHeader 三个情绪识别的表头
     * @param fileName    文件名
     * @param sheetName   sheet页
     * @return
     * @throws Exception
     */
    public static void createEALLExcelFile(List<Class> clazzs, Map<String, List> objs, JSONObject resultJson, List<Map<Integer, List<ExcelBean>>> tableHeader, String fileName, String sheetName) throws Exception {
        // 创建新的Excel工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 在Excel工作簿中建一工作表，其名为缺省值, 也可以指定Sheet名称
        XSSFSheet sheet = workbook.createSheet(sheetName);
        // 以下为excel的字体样式以及excel的标题与内容的创建，下面会具体分析;
        //字体样式
        createFont(workbook);
        //创建内容
        createEALLTableRows(sheet, objs, tableHeader, resultJson, clazzs);
        FileOutputStream fileOutputStream = null;
        if (OSUtil.isLinux()) {
            File file = new File("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName);
            if (!file.exists()) {
                file.mkdirs();
            }
            fileOutputStream = new FileOutputStream("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName + "/" + fileName);
        } else {
            File file = new File("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName);
            if (!file.exists()) {
                file.mkdirs();
            }
            fileOutputStream = new FileOutputStream("./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + sheetName + "/" + fileName);
        }
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        //return workbook;
    }

    private static void createEALLTableRows(XSSFSheet sheet, Map<String, List> objsMap, List<Map<Integer, List<ExcelBean>>> tableHeader, JSONObject resultJson, List<Class> clazzs) throws Exception {
        int rowindex = 0;
        for (int j = 0; j < tableHeader.size(); j++) {
            Map<Integer, List<ExcelBean>> map = tableHeader.get(j);
            Class clazz = clazzs.get(j);
            List objs = null;
            Map<String, String> resultMap = null;
            if (j == 0) {
                objs = objsMap.get("ECAT");
                resultMap = (Map<String, String>) resultJson.get("ECAT");
            } else if (j == 1) {
                rowindex += 5;
                objs = objsMap.get("EREC");
                resultMap = (Map<String, String>) resultJson.get("EREC");
            } else if (j == 2) {
                rowindex += 5;
                objs = objsMap.get("EMEM");
                resultMap = (Map<String, String>) resultJson.get("EMEM");
            }
            //创建标题（头）
            XSSFRow titleRow1 = sheet.createRow(rowindex);
            for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
                List<ExcelBean> excels = entry.getValue();
                for (int x = 0; x < excels.size(); x++) {
                    XSSFCell cellTitle = titleRow1.createCell(x);
                    cellTitle.setCellValue(excels.get(x).headTextName);
                    cellTitle.setCellStyle(fontStyle);
                }
            }
            rowindex++;
            int maxKey = 0;
            List<ExcelBean> ems = new ArrayList<>();
            for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
                if (entry.getKey() > maxKey) {
                    maxKey = entry.getKey();
                }
            }
            ems = map.get(maxKey);
            List<Integer> widths = new ArrayList<Integer>(ems.size());
            //渲染答题记录
            if (objs != null) {
                for (Object obj : objs) {
                    XSSFRow row = sheet.createRow(rowindex);
                    for (int i = 0; i < ems.size(); i++) {
                        ExcelBean em = (ExcelBean) ems.get(i);
                        String propertyName = em.getPropertyName();
                        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyName, clazz);
                        Method method = propertyDescriptor.getReadMethod();
                        Object rtn = method.invoke(obj);
                        String value = "";
                        // 如果是日期类型进行转换
                        if (rtn != null) {
                            if (rtn instanceof Date) {
                                value = new SimpleDateFormat("yyyy-MM-dd").format(rtn);
                            } else if (rtn instanceof BigDecimal) {
                                NumberFormat nf = new DecimalFormat("#,##0.00");
                                value = nf.format((BigDecimal) rtn).toString();
                            } else if ((rtn instanceof Integer) && (Integer.valueOf(rtn.toString()) < 0)) {
                                value = "--";
                            } else {
                                value = rtn.toString();
                                if (clazz.equals(ECATEntity.class)) {
                                    if (propertyName.equals("userSelectWordType")) {
                                        if (value.equals("1")) {
                                            value = "积极";
                                        }
                                        if (value.equals("0")) {
                                            value = "消极";
                                        }
                                    }
                                }
                                if (clazz.equals(EMEMEntity.class)) {
                                    if (propertyName.equals("appearedOrNot")) {
                                        if (value.equals("0")) {
                                            value = "否";
                                        }
                                        if (value.equals("1")) {
                                            value = "是";
                                        }
                                    }
                                    if (propertyName.equals("correct")) {
                                        if (value.equals("0")) {
                                            value = "错误";
                                        }
                                        if (value.equals("1")) {
                                            value = "正确";
                                        }
                                    }
                                }
                            }
                        }
                        XSSFCell cell = row.createCell(i);
                        cell.setCellValue(value);
                        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                        cell.setCellStyle(fontStyle2);
                        // 获得最大列宽
                        int width = value.getBytes().length * 300;
                        // 还未设置，设置当前
                        if (widths.size() <= i) {
                            widths.add(width);
                            continue;
                        }
                        // 比原来大，更新数据
                        if (width > widths.get(i)) {
                            widths.set(i, width);
                        }
                    }
                    rowindex++;
                }
            }
            rowindex += 2;
            if (resultMap != null && resultMap.size() > 0) {
                //渲染最终各项得分
                XSSFRow titleRow = sheet.createRow(rowindex);
                rowindex += 1;
                XSSFRow scoreRow = sheet.createRow(rowindex);
                int i = 0;
                if (resultMap.size() > 0) {
                    for (Map.Entry<String, String> entry : resultMap.entrySet()) {
                        XSSFCell cellTitle = titleRow.createCell(i);
                        cellTitle.setCellValue(entry.getKey());
                        cellTitle.setCellType(XSSFCell.CELL_TYPE_STRING);
                        cellTitle.setCellStyle(fontStyle2);
                        XSSFCell cellScore = scoreRow.createCell(i);
                        cellScore.setCellValue(entry.getValue());
                        cellScore.setCellType(XSSFCell.CELL_TYPE_STRING);
                        cellScore.setCellStyle(fontStyle2);
                        i++;
                    }
                }
            }

            // 设置列宽
            for (int index = 0; index < widths.size(); index++) {
                Integer width = widths.get(index);
                width = width < 2500 ? 2500 : width + 300;
                width = width > 10000 ? 10000 + 300 : width + 300;
                sheet.setColumnWidth(index, width);
            }
        }

    }

    private static void createEALLTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, int rowindex) {

        ////cell起始位置
        //int startIndex = 0;
        ////cell终止位置
        //int endIndex = 0;
        //for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
        //    XSSFRow row = sheet.createRow(entry.getKey());
        //    List<ExcelBean> excels = entry.getValue();
        //    for (int x = 0; x < excels.size(); x++) {
        //        //合并单元格
        //        //if (excels.get(x).getCols() > 1) {
        //        if (x == 0) {
        //            endIndex += excels.get(x).getCols() - 1;
        //            CellRangeAddress range = new CellRangeAddress(rowindex - 1, rowindex - 1, startIndex, endIndex);
        //            sheet.addMergedRegion(range);
        //        } else {
        //            endIndex += excels.get(x).getCols();
        //            CellRangeAddress range = new CellRangeAddress(rowindex - 1, rowindex - 1, startIndex, endIndex);
        //            sheet.addMergedRegion(range);
        //        }
        //        startIndex += excels.get(x).getCols();
        //        XSSFCell cell = row.createCell(startIndex - excels.get(x).getCols());
        //        // 设置内容
        //        cell.setCellValue(excels.get(x).getHeadTextName());
        //        if (excels.get(x).getCellStyle() != null) {
        //            // 设置格式
        //            cell.setCellStyle(excels.get(x).getCellStyle());
        //        }
        //        cell.setCellStyle(fontStyle);
        //        //} else {
        //        //    XSSFCell cell = row.createCell(x);
        //        //    // 设置内容
        //        //    cell.setCellValue(excels.get(x).getHeadTextName());
        //        //    if (excels.get(x).getCellStyle() != null) {
        //        //        // 设置格式
        //        //        cell.setCellStyle(excels.get(x).getCellStyle());
        //        //    }
        //        //    cell.setCellStyle(fontStyle);
        //        //}
        //    }
        //}
    }


    /**
     * @param clazz
     * @param objs
     * @param resultMap
     * @param map
     * @param fileName
     * @return
     * @throws Exception
     */
    public static XSSFWorkbook createExcelFileForPublic(Class clazz, List objs, List<Map<String, String>> resultMap, Map<Integer, List<ExcelBean>> map, String fileName, String filePath) throws Exception {
        // 创建新的Excel工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 在Excel工作簿中建一工作表，其名为缺省值, 也可以指定Sheet名称
        XSSFSheet sheet = workbook.createSheet("用户信息");
        // 以下为excel的字体样式以及excel的标题与内容的创建，下面会具体分析;
        //字体样式
        createFont(workbook);
        //创建标题（头）
        createTableHeader(sheet, map);
        //创建内容
        createTableRows(sheet, map, objs, resultMap, clazz);
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        FileOutputStream fileOutputStream = null;
        File file = new File(filePath);
        if (!file.exists()) {
            //file.createNewFile();
            file.mkdirs();
        }
        fileOutputStream = new FileOutputStream(filePath + fileName);
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        return workbook;
    }


    private static XSSFCellStyle fontStyle;
    private static XSSFCellStyle fontStyle2;

    public static void createFont(XSSFWorkbook workbook) {
        // 表头
        fontStyle = workbook.createCellStyle();
        XSSFFont font1 = workbook.createFont();
        font1.setBold(true);
        font1.setFontName("黑体");
        // 设置字体大小
        font1.setFontHeightInPoints((short) 14);
        fontStyle.setFont(font1);
        // 下边框
        fontStyle.setBorderBottom(BorderStyle.THIN);
        // 左边框
        fontStyle.setBorderLeft(BorderStyle.THIN);
        // 上边框
        fontStyle.setBorderTop(BorderStyle.THIN);
        // 右边框
        fontStyle.setBorderRight(BorderStyle.THIN);
        // 居中
        fontStyle.setAlignment(HorizontalAlignment.CENTER);
        // 内容
        fontStyle2 = workbook.createCellStyle();
        XSSFFont font2 = workbook.createFont();
        font2.setFontName("宋体");
        // 设置字体大小
        font2.setFontHeightInPoints((short) 10);
        fontStyle2.setFont(font2);
        // 下边框
        fontStyle2.setBorderBottom(BorderStyle.THIN);
        // 左边框
        fontStyle2.setBorderLeft(BorderStyle.THIN);
        // 上边框
        fontStyle2.setBorderTop(BorderStyle.THIN);
        // 右边框
        fontStyle2.setBorderRight(BorderStyle.THIN);
        // 居中
        fontStyle2.setAlignment(HorizontalAlignment.CENTER);
    }

    /**
     * 根据ExcelMapping 生成列头（多行列头）
     *
     * @param sheet 工作簿
     * @param map   每行每个单元格对应的列头信息
     */
    private static final void createTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map) {
        //cell起始位置
        int startIndex = 0;
        //cell终止位置
        int endIndex = 0;
        for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
            XSSFRow row = sheet.createRow(entry.getKey());
            List<ExcelBean> excels = entry.getValue();
            for (int x = 0; x < excels.size(); x++) {
                //合并单元格
                if (excels.get(x).getCols() > 1) {
                    if (x == 0) {
                        endIndex += excels.get(x).getCols() - 1;
                        CellRangeAddress range = new CellRangeAddress(0, 0, startIndex, endIndex);
                        sheet.addMergedRegion(range);
                    } else {
                        endIndex += excels.get(x).getCols();
                        CellRangeAddress range = new CellRangeAddress(0, 0, startIndex, endIndex);
                        sheet.addMergedRegion(range);
                    }
                    startIndex += excels.get(x).getCols();
                    XSSFCell cell = row.createCell(startIndex - excels.get(x).getCols());
                    // 设置内容
                    cell.setCellValue(excels.get(x).getHeadTextName());
                    if (excels.get(x).getCellStyle() != null) {
                        // 设置格式
                        cell.setCellStyle(excels.get(x).getCellStyle());
                    }
                    cell.setCellStyle(fontStyle);
                } else {
                    XSSFCell cell = row.createCell(x);
                    // 设置内容
                    cell.setCellValue(excels.get(x).getHeadTextName());
                    if (excels.get(x).getCellStyle() != null) {
                        // 设置格式
                        cell.setCellStyle(excels.get(x).getCellStyle());
                    }
                    cell.setCellStyle(fontStyle);
                }
            }
        }
    }

    /**
     * @param sheet     表格sheet页
     * @param map       表头
     * @param objs      答题列表
     * @param clazz     量表实体类
     * @param resultMap 测试结果得分
     * @throws Exception
     */
    private static void createTableRows(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, List objs, List<Map<String, String>> resultMap, Class clazz) throws Exception {
        int rowindex = map.size();
        int maxKey = 0;
        List<ExcelBean> ems = new ArrayList<>();
        for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
            if (entry.getKey() > maxKey) {
                maxKey = entry.getKey();
            }
        }
        ems = map.get(maxKey);
        List<Integer> widths = new ArrayList<Integer>(ems.size());
        //渲染答题记录
        if (objs != null) {
            for (Object obj : objs) {
                XSSFRow row = sheet.createRow(rowindex);
                for (int i = 0; i < ems.size(); i++) {
                    ExcelBean em = (ExcelBean) ems.get(i);
                    String propertyName = em.getPropertyName();
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyName, clazz);
                    Method method = propertyDescriptor.getReadMethod();
                    Object rtn = method.invoke(obj);
                    String value = "";
                    // 如果是日期类型进行转换
                    if (rtn != null) {

                        if (rtn instanceof Date) {
                            value = new SimpleDateFormat("yyyy-MM-dd").format(rtn);
                        } else if (rtn instanceof BigDecimal) {
                            NumberFormat nf = new DecimalFormat("#,##0.00");
                            value = nf.format((BigDecimal) rtn).toString();
                        } else if ((rtn instanceof Integer) && (Integer.valueOf(rtn.toString()) < 0)) {
                            value = "--";
                        } else {
                            value = rtn.toString();
                            if (clazz.equals(ScaleEntity.class)) {
                                if (propertyName.equals("questionType")) {
                                    if (value.equals("0")) {
                                        value = "单选";
                                    } else if (value.equals("1")) {
                                        value = "多选";
                                    } else if (value.equals("2")) {
                                        value = "文本";
                                    } else if (value.equals("3")) {
                                        value = "数字";
                                    } else if (value.equals("4")) {
                                        value = "日期";
                                    } else if (value.equals("5")) {
                                        value = "下拉选";
                                    } else if (value.equals("6")) {
                                        value = "跳转单选";
                                    } else if (value.equals("7")) {
                                        value = "说明单选";
                                    } else if (value.equals("8")) {
                                        value = "附图单选";
                                    } else if (value.equals("9")) {
                                        value = "附图多选";
                                    } else if (value.equals("10")) {
                                        value = "附说明单选";
                                    } else if (value.equals("11")) {
                                        value = "附说明多选";
                                    }
                                }
                                if (propertyName.equals("scoreDirection")) {
                                    if (value.equals("1")) {
                                        value = "正向";
                                    } else if (value.equals("0")) {
                                        value = "反向";
                                    }
                                }
                            }
                            if (clazz.equals(ASKEntity.class) || clazz.equals(MoodEntity.class) || clazz.equals(StatusEntity.class)) {
                                if (propertyName.equals("checkItems")) {
                                    if (value.equals("yes")) {
                                        value = "是";
                                    } else if (value.equals("no")) {
                                        value = "否";
                                    }
                                }
                                if (propertyName.equals("type")) {
                                    if (value.equals("1")) {
                                        value = "正向";
                                    } else if (value.equals("0")) {
                                        value = "反向";
                                    }
                                }
                            }
                            //类型：1紧张；2愤怒；3疲劳；4:抑郁；5精力；6慌乱；7自我情绪相关
                            if (clazz.equals(POMSEntity.class)) {
                                if (propertyName.equals("type")) {
                                    if (value.equals("1")) {
                                        value = "紧张";
                                    } else if (value.equals("2")) {
                                        value = "愤怒";
                                    } else if (value.equals("3")) {
                                        value = "疲劳";
                                    } else if (value.equals("4")) {
                                        value = "抑郁";
                                    } else if (value.equals("5")) {
                                        value = "精力";
                                    } else if (value.equals("6")) {
                                        value = "慌乱";
                                    } else if (value.equals("7")) {
                                        value = "自我情绪";
                                    }
                                }
                            }
                            //分量编号 0躯体化 1强迫症状 2人际关系敏感 3抑郁 4焦虑 5敌对 6恐怖 7偏执 8精神病性 9 其他
                            if (clazz.equals(SCLEntity.class)) {
                                if (propertyName.equals("type")) {
                                    if (value.equals("0")) {
                                        value = "躯体化";
                                    } else if (value.equals("1")) {
                                        value = "强迫症状";
                                    } else if (value.equals("2")) {
                                        value = "人际关系敏感";
                                    } else if (value.equals("3")) {
                                        value = "抑郁";
                                    } else if (value.equals("4")) {
                                        value = "焦虑";
                                    } else if (value.equals("5")) {
                                        value = "敌对";
                                    } else if (value.equals("6")) {
                                        value = "恐怖";
                                    } else if (value.equals("7")) {
                                        value = "偏执";
                                    } else if (value.equals("8")) {
                                        value = "精神病性";
                                    } else if (value.equals("9")) {
                                        value = "其他";
                                    }
                                }
                            }
                            //类型 1压力指数  2焦虑指数  3抑郁指数
                            if (clazz.equals(DepressEntity.class)) {
                                if (propertyName.equals("type")) {
                                    if (value.equals("1")) {
                                        value = "压力指数";
                                    } else if (value.equals("2")) {
                                        value = "焦虑指数";
                                    } else if (value.equals("3")) {
                                        value = "抑郁指数";
                                    }
                                }
                            }
                            if (clazz.equals(MemoryEntity.class)) {
                                if (propertyName.equals("backCount")) {
                                    value = value + "-back";
                                }
                                if (propertyName.equals("groupCount")) {
                                    value = Integer.parseInt(value) + 1 + "";
                                }
                                if (propertyName.equals("charShowCount")) {
                                    value = Integer.parseInt(value) + 1 + "";
                                }
                            }
                            if (clazz.equals(ANTEntity.class)) {
                                if (propertyName.equals("consistency")) {
                                    if (value.equals("1")) {
                                        value = "一致性刺激";
                                    }
                                    if (value.equals("0")) {
                                        value = "不一致性刺激";
                                    }
                                }
                            }
                            if (clazz.equals(BSNTaskEntity.class)) {
                                if (propertyName.equals("picChoice")) {
                                    if (value.equals("1")) {
                                        value = "正确";
                                    }
                                    if (value.equals("2")) {
                                        value = "提示";
                                    }
                                    if (value.equals("3")) {
                                        value = "辨认";
                                    }
                                    if (value.equals("4")) {
                                        value = "错误";
                                    }
                                }
                            }
                            if (clazz.equals(ETB01Entity.class)) {
                                if (propertyName.equals("correct")) {
                                    if (value.equals("True")) {
                                        value = "正确";
                                    }
                                    if (value.equals("False")) {
                                        value = "错误";
                                    }
                                }
                            }
                            if (clazz.equals(ECATEntity.class)) {
                                if (propertyName.equals("userSelectWordType")) {
                                    if (value.equals("1")) {
                                        value = "积极";
                                    }
                                    if (value.equals("0")) {
                                        value = "消极";
                                    }
                                }
                            }
                            if (clazz.equals(EMEMEntity.class)) {
                                if (propertyName.equals("appearedOrNot")) {
                                    if (value.equals("0")) {
                                        value = "否";
                                    }
                                    if (value.equals("1")) {
                                        value = "是";
                                    }
                                }
                                if (propertyName.equals("correct")) {
                                    if (value.equals("0")) {
                                        value = "错误";
                                    }
                                    if (value.equals("1")) {
                                        value = "正确";
                                    }
                                }
                            }
                            if (clazz.equals(FDOTEntity.class)) {
                                if (propertyName.equals("correct")) {
                                    if (value.equals("1")) {
                                        value = "正确";
                                    }
                                    if (value.equals("0")) {
                                        value = "错误";
                                    }
                                }
                                if (propertyName.equals("type")) {
                                    if (value.equals("0")) {
                                        value = "block1";
                                    }
                                    if (value.equals("1")) {
                                        value = "block2";
                                    }
                                }
                                if (propertyName.equals("dotPos")) {
                                    if (value.equals("0")) {
                                        value = "上方";
                                    }
                                    if (value.equals("1")) {
                                        value = "下方";
                                    }
                                }
                            }
                        }
                    }
                    XSSFCell cell = row.createCell(i);
                    cell.setCellValue(value);
                    cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                    cell.setCellStyle(fontStyle2);
                    // 获得最大列宽
                    int width = value.getBytes().length * 300;
                    // 还未设置，设置当前
                    if (widths.size() <= i) {
                        widths.add(width);
                        continue;
                    }
                    // 比原来大，更新数据
                    if (width > widths.get(i)) {
                        widths.set(i, width);
                    }
                }
                rowindex++;
            }
        }
        rowindex += 2;
        if (resultMap != null && resultMap.size() > 0) {
            for (int m = 0; m < resultMap.size(); m++) {
                Map<String, String> hashMap = resultMap.get(m);
                if (hashMap != null && hashMap.size() > 0) {
                    //渲染最终各项得分
                    XSSFRow titleRow = sheet.createRow(rowindex);
                    rowindex += 1;
                    XSSFRow scoreRow = sheet.createRow(rowindex);
                    int i = 0;
                    if (resultMap.size() > 0) {
                        for (Map.Entry<String, String> entry : hashMap.entrySet()) {
                            XSSFCell cellTitle = titleRow.createCell(i);
                            cellTitle.setCellValue(entry.getKey());
                            cellTitle.setCellType(XSSFCell.CELL_TYPE_STRING);
                            cellTitle.setCellStyle(fontStyle2);
                            XSSFCell cellScore = scoreRow.createCell(i);
                            cellScore.setCellValue(entry.getValue());
                            cellScore.setCellType(XSSFCell.CELL_TYPE_STRING);
                            cellScore.setCellStyle(fontStyle2);
                            i++;
                        }
                    }
                }
                rowindex += 2;
            }
        }

        // 设置列宽
        for (int index = 0; index < widths.size(); index++) {
            Integer width = widths.get(index);
            width = width < 2500 ? 2500 : width + 300;
            width = width > 10000 ? 10000 + 300 : width + 300;
            sheet.setColumnWidth(index, width);
        }
    }


    /**
     * 用户导入
     *
     * @param in
     * @param fileName
     * @return
     * @throws Exception
     */
    public static List<List<Object>> getBankListByExcelForUserImport(InputStream in, String fileName) throws Exception {
        List<List<Object>> list = null;
        //创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        System.out.println("work.getNumberOfSheets()：" + work.getNumberOfSheets());
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            int sheetSize = 0;
            //遍历当前sheet中的所有行
            //包涵头部，所以要小于等于最后一列数,这里也可以在初始值加上头部行数，以便跳过头部
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                //读取一行
                row = sheet.getRow(j);
                //去掉空行和表头
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }
                sheetSize = row.getLastCellNum();
                //判断当前行是否为空
                if (isRowEmpty(row)) {
                    continue;
                }
                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < sheetSize; y++) {
                    cell = row.getCell(y);
                    li.add(cell != null ? getCellValue(cell) : null);
                }
                list.add(li);
            }
        }
        return list;
    }

    /**
     * 判断行是否为空
     *
     * @param row 行
     * @return true:空 ；false：非空
     */
    public static boolean isRowEmpty(Row row) {

        for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
                return false;
            } else {
                break;
            }
        }
        return true;
    }
}
