数据导出成Excel表格

` Controller层
@PostMapping(value = "/exportPlanDemandList")
@ApiOperation("需求条目导出")
@AdviceLog(value = "需求条目导出", type = LogType.OPERATE, operateType = LogOperateType.EXPORT)
public void exportDemandList(@RequestBody DemandPlanListVo vo, OutputStream out) {
    try {
        String sheetName = "需求条目";
        // 获取所需数据的分页
        Pager pager = demandPlanListService.getDemandListPage(vo);
        List<Map<String, Object>> list = ConvertUtils.listConvert(pager.getRows());
        String[] excelTilte = BasisFormationConstant.excelDemandList2;
        String[] headerTitle = Arrays.stream(excelTilte).map(e -> e.split(":")[1]).toArray(size -> new String[size]);
        String[] headerValues = Arrays.stream(excelTilte).map(e -> e.split(":")[0]).toArray(size -> new String[size]);
        ExcelUtil.exportExcel2007WithSXSSF(sheetName, headerTitle, headerValues, list, out, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
复制代码

public class ConvertUtils {
    private static final String CHINA_GREEN = "绿色";
    private static final String ENG_GREEN = "green";

    private static final String CHINA_RED = "红色";
    private static final String ENG_RED = "red";

    private static final String CHINA_ORANGE = "橙色";
    private static final String ENG_ORANGE = "orange";

    private static final String CHINA_PURPLE = "紫色";
    private static final String ENG_PURPLE = "purple";

    private static final String CHINA_YELLOW = "黄色";
    private static final String ENG_YELLOW = "yellow";

    private static final String CHINA_BLUE = "蓝色";
    private static final String ENG_BLUE = "#0c60aa";





    /**
     * list克隆
     *
     * @param sources
     * @param c
     * @param <E>
     * @param <T>
     * @return
     */
    public static <E, T> List<T> convertList(List<E> sources, Class<T> c) {
        if (CollectionUtils.isEmpty(sources)) {
            return new ArrayList<T>();
        }
        List<T> list = new ArrayList<T>();
        for (E source : sources) {
            list.add(convertBean(source, c));
        }
        return list;
    }
    /**
     * param convert entity
     * @param param
     * @param tClass
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T, E> T convertBean(E param, Class<T> tClass) {
        try {
            if (param == null) {
                return tClass.newInstance();
            }
            T instance = tClass.newInstance();
            BeanUtils.copyProperties(param, instance);
            return instance;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> List<Map<String, Object>> listConvert(List<T> list) {
        // 定义List<Map<String, Object>>数组<br>          
        // list为外部传进来的list集合
        List<Map<String, Object>> list_map = new ArrayList<Map<String, Object>>();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(list)) {
            //PropertyUtils.describe(Object)转换
            list.forEach(item -> {
                Map<String, Object> map = null;
                try {
                    map = (Map<String, Object>) PropertyUtils.describe(item);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
                list_map.add(map);
            });
        }
        return list_map;
    }

    public static String convertBinaryColor(String color){
        if(StringUtil.isNotEmpty(color)){
            color=color.replace(CHINA_GREEN,ENG_GREEN);
            color=color.replace(CHINA_RED,ENG_RED);
            color=color.replace(CHINA_ORANGE,ENG_ORANGE);
            color=color.replace(CHINA_PURPLE,ENG_PURPLE);
            color=color.replace(CHINA_YELLOW,ENG_YELLOW);
            color=color.replace(CHINA_BLUE,ENG_BLUE);
        }
        return color;
    }


    //得到当前用户密级程度
    public static String convert(TSUser user){
         
    if(user.getSecurityLevel() != null){
      if (Globals.SecretLevel_One.shortValue() == user.getSecurityLevel())
        {
            return "非密";
        }
        else if (Globals.SecretLevel_Two.shortValue() == user.getSecurityLevel())
        {
           return "一般";
        }
        else if (Globals.SecretLevel_Three.shortValue() == user.getSecurityLevel())
        {
           return "重要";
        }
        else if (Globals.SecretLevel_Four.shortValue() == user.getSecurityLevel())
        {
           return "核心";
        }
        else
        {
           return "非密";
        }
     }
             return "空";
    }
    
    
    /**
     * 特殊将字符串转义
     * @param value
     * @return
     */
    public static String escapeStr(String value)
    {   
        StringBuffer result=new StringBuffer();
        if(value == null){
            return null;
        }else{
        char content[] = new char[value.length()];
        value.getChars(0, value.length(), content, 0);
        result = new StringBuffer(content.length + 50);
        for(int i = 0; i < content.length; i++)
            switch(content[i])
            {
            case 34: // '"'
                result.append("&quot;");
                break;

            case 38: // '&'
                result.append("&amp;");
                break;

            case 39: // '''
                result.append("&#39;");
                break;          

            case 60: // '<'
                result.append("&lt;");
                break;

            case 62: // '>'
                result.append("&gt;");
                break;

            default:
                result.append(content[i]);
                break;
            }
        }
        return result.toString();
    }
   
}
复制代码
// 常量类
public class BasisFormationConstant {
    public static final String[] excelDemandList2 = new String[] {
        "num:编号",
        "demandName:需求名称",
        "demandCategoryName:需求类别",
        "demandLevel:对应层级",
        "demandTypeName:需求验证类型",
        "demandProduct:承接产品",
        "remark:说明",
        "resourceName:需求来源",
        "verifyStatus:验证状态",
        "demandStatus:需求状态",
        "isIcon:是否包含图标",
        "createTime:创建时间"
    };
}
复制代码
public class ExcelUtil {

    // 2003 版本 最大支持65536 行
    public  final static String  EXCEL_FILE_2003 = "2003";
    // 2007 版本以上 最大支持1048576行
    public  final static String  EXCEl_FILE_2007 = "2007";
    // 2007 版本以上 大数据量导出
    public  final static String  EXCEl_FILE_2007_SXSSF = "2007_SXSSF";

    /**
     * <p>
     * 导出无头部标题行Excel <br>
     * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     *
     * @param title 表格标题
     * @param headersField 表格字段集合
     * @param dataList 数据集合
     * @param out 输出流
     * @param version 2003 或者 2007,不传时默认生成2003版本
     * @throws IOException
     */
    public static void exportExcel(String title, String[] headersField, List<Map<String, Object>> dataList, OutputStream out,
                                   String version) throws IOException {
        if (StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())) {
            exportExcel2003(title, null, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
        } else if(EXCEl_FILE_2007_SXSSF.equals(version.trim())) {
            exportExcel2007WithSXSSF(title, null, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
        } else {
            exportExcel2007(title, null, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
        }
    }

    /**
     * <p>
     * 导出带有头部标题行的Excel <br>
     * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     *
     * @param title 表格标题
     * @param headers 头部标题集合
     * @param headersField 表格头部标题对应的字段集合
     * @param dataList 数据集合
     * @param out 输出流
     * @param version 2003 或者 2007,不传时默认生成2003版本
     * @throws IOException
     */
    public static void exportExcel(String title, String[] headers, String[] headersField, List<Map<String, Object>> dataList,
                                   OutputStream out, String version) throws IOException {
        if (StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())) {
            exportExcel2003(title, headers, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
        } else if(EXCEl_FILE_2007_SXSSF.equals(version.trim())) {
            exportExcel2007WithSXSSF(title, headers, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
        } else {
            exportExcel2007(title, headers, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
        }
    }

    /**
     * <p>
     * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
     * 此版本生成2007以上版本的文件 (文件后缀:xlsx)
     * </p>
     *
     * @param title
     *            表格标题名
     * @param headers
     *            表格头部标题集合
     * @param headersField
     *            表格头部标题对应的字段集合
     * @param dataList
     *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *            JavaBean属性的数据类型有基本数据类型及String,Date
     * @param out
     *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern
     *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     * @throws IOException
     */
    public static void exportExcel2007WithSXSSF(String title, String[] headers, String[] headersField,
                                                List<Map<String, Object>> dataList, OutputStream out, String pattern) throws IOException {

        SXSSFWorkbook workbook = null;
        try {
            // 声明一个工作薄
            workbook = new SXSSFWorkbook();
            // 生成一个表格
            Sheet sheet = workbook.createSheet(title);
            sheet.setDefaultColumnWidth(30);
            // 生成一个样式
            CellStyle headerStyle = workbook.createCellStyle();
            // 设置这些样式
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            // 生成一个字体
            org.apache.poi.ss.usermodel.Font font = workbook.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 16);
            headerStyle.setFont(font);

            // 生成并设置另一个样式
            CellStyle dataStyle = workbook.createCellStyle();
           /* dataStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            dataStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);*/
            // 生成另一个字体
            org.apache.poi.ss.usermodel.Font font2 = workbook.createFont();
            dataStyle.setFont(font2);

            // 产生表格标题行
            Row row = sheet.createRow(0);
            Cell cellHeader;
            if(headers!=null){
                for (int i = 0; i < headers.length; i++) {
                    cellHeader = row.createCell(i);
                    cellHeader.setCellStyle(headerStyle);
                    cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
                }
            }

            // 遍历集合数据,产生数据行
            Iterator<Map<String, Object>> it = dataList.iterator();
            Map<String, Object> map;
            int index = 0;
            Object value;
            String textValue;
            Cell cell;
            Matcher matcher;
            Pattern p = Pattern.compile("^//d+(//.//d+)?$");
            SimpleDateFormat sdf=null;
            if(StringUtils.isNotEmpty(pattern)){
                sdf = new SimpleDateFormat(pattern);
            }else{
                sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            }
            while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                map = (Map<String,Object>) it.next();
                for (int n = 0; n < headersField.length; n++) {
                    cell = row.createCell(n);
                    cell.setCellStyle(dataStyle);
                    value = map.get(headersField[n]);
                    // 判断值的类型后进行强制类型转换
                    textValue = null;
                    if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof Float) {
                        textValue = String.valueOf((Float) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Double) {
                        textValue = String.valueOf((Double) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Long) {
                        cell.setCellValue((Long) value);
                    }
                    if (value instanceof Boolean) {
                        textValue = "是";
                        if (!(Boolean) value) {
                            textValue = "否";
                        }
                    } else if (value instanceof Date) {
                        textValue = sdf.format((Date) value);
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        if (value != null) {
                            textValue = value.toString();
                        }
                    }
                    if (textValue != null) {
                        matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            cell.setCellValue(textValue);
                        }
                    }
                }
            }

            workbook.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }finally {
            if(workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * <p>
     * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
     * 此版本生成2007以上版本的文件 (文件后缀:xlsx)
     * </p>
     *
     * @param title
     *            表格标题名
     * @param headers
     *            表格头部标题集合
     * @param headersField
     *            表格头部标题对应的字段集合
     * @param dataList
     *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *            JavaBean属性的数据类型有基本数据类型及String,Date
     * @param out
     *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern
     *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     * @throws IOException
     */
    public static void exportExcel2007(String title, String[] headers, String[] headersField,
                                       List<Map<String, Object>> dataList, OutputStream out, String pattern) throws IOException {

        XSSFWorkbook workbook = null;
        try {
            // 声明一个工作薄
            workbook = new XSSFWorkbook();
            // 生成一个表格
            XSSFSheet sheet = workbook.createSheet(title);
            // 设置表格默认列宽度为30个字节
            sheet.setDefaultColumnWidth(30);
            // 生成一个样式
            XSSFCellStyle headerStyle = workbook.createCellStyle();
            // 设置这些样式
            headerStyle.setFillForegroundColor(new XSSFColor(new Color(217, 217, 217)));
            // 生成一个字体
            XSSFFont font = workbook.createFont();
            font.setFontName("宋体");
            font.setColor(new XSSFColor(Color.BLACK));
            font.setFontHeightInPoints((short) 16);
            // 把字体应用到当前的样式
            headerStyle.setFont(font);

            // 生成并设置另一个样式
            XSSFCellStyle dataStyle = workbook.createCellStyle();
        /*    dataStyle.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
            dataStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);*/
            // 生成另一个字体
            XSSFFont font2 = workbook.createFont();
            // 把字体应用到当前的样式
            dataStyle.setFont(font2);

            // 产生表格标题行
            XSSFRow row = sheet.createRow(0);
            XSSFCell cellHeader;
            if(headers!=null){
                for (int i = 0; i < headers.length; i++) {
                    cellHeader = row.createCell(i);
                    cellHeader.setCellStyle(headerStyle);
                    cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
                }
            }


            // 遍历集合数据,产生数据行
            Iterator<Map<String, Object>> it = dataList.iterator();
            Map<String, Object> map;
            int index = 0;
            Object value;
            String textValue;
            XSSFCell cell;
            XSSFRichTextString richString;
            Matcher matcher;
            Pattern p = Pattern.compile("^//d+(//.//d+)?$");
            SimpleDateFormat sdf=null;
            if(StringUtils.isNotEmpty(pattern)){
                sdf = new SimpleDateFormat(pattern);
            }else{
                sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            }
            while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                map = (Map<String,Object>) it.next();
                for (int n = 0; n < headersField.length; n++) {
                    cell = row.createCell(n);
                    cell.setCellStyle(dataStyle);
                    value = map.get(headersField[n]);
                    // 判断值的类型后进行强制类型转换
                    textValue = null;
                    if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof Float) {
                        textValue = String.valueOf((Float) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Double) {
                        textValue = String.valueOf((Double) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Long) {
                        cell.setCellValue((Long) value);
                    }
                    if (value instanceof Boolean) {
                        textValue = "是";
                        if (!(Boolean) value) {
                            textValue = "否";
                        }
                    } else if (value instanceof Date) {
                        textValue = sdf.format((Date) value);
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        if (value != null) {
                            textValue = value.toString();
                        }
                    }
                    if (textValue != null) {
                        matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            richString = new XSSFRichTextString(textValue);
                            cell.setCellValue(richString);
                        }
                    }
                }
            }

            workbook.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }finally {
            if(workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * <p>
     * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
     * 此方法生成2003版本的excel,文件名后缀:xls <br>
     * </p>
     *
     * @param title
     *            表格标题名
     * @param headers
     *            表格头部标题集合
     * @param headersField
     *            表格头部标题对应的字段集合
     * @param dataList
     *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *            JavaBean属性的数据类型有基本数据类型及String,Date
     * @param out
     *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern
     *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     * @throws IOException
     */
    public static void exportExcel2003(String title, String[] headers, String[] headersField,
                                       List<Map<String, Object>> dataList, OutputStream out, String pattern) throws IOException {

        HSSFWorkbook workbook = null;
        try {
            // 声明一个工作薄
            workbook = new HSSFWorkbook();
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet(title);
            // 设置表格默认列宽度为20个字节
            sheet.setDefaultColumnWidth(20);
            // 生成一个样式
            HSSFCellStyle headerStyle = workbook.createCellStyle();
            // 设置这些样式
            // 生成一个字体
            HSSFFont font = workbook.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 11);
            // 把字体应用到当前的样式
            headerStyle.setFont(font);

            // 生成并设置另一个样式
            HSSFCellStyle dataStyle = workbook.createCellStyle();
            // 生成另一个字体
            HSSFFont font2 = workbook.createFont();
            // 把字体应用到当前的样式
            dataStyle.setFont(font2);

            // 产生表格标题行
            HSSFRow row = sheet.createRow(0);
            HSSFCell cellHeader;
            if(headers!=null && headers.length>0){
                for (int i = 0; i < headers.length; i++) {
                    cellHeader = row.createCell(i);
                    cellHeader.setCellStyle(headerStyle);
                    cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
                }
            }

            // 遍历集合数据,产生数据行
            Iterator<Map<String,Object>> it = dataList.iterator();
            Map<String,Object> map;
            int index = 0;
            Object value;
            String textValue;
            HSSFCell cell;
            HSSFRichTextString richString;
            Matcher matcher;
            Pattern p = Pattern.compile("^//d+(//.//d+)?$");
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                map = (Map<String,Object>) it.next();
                for (int n = 0; n < headersField.length; n++) {
                    cell = row.createCell(n);
                    cell.setCellStyle(dataStyle);
                    value = map.get(headersField[n]);
                    // 判断值的类型后进行强制类型转换
                    textValue = null;
                    if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof Float) {
                        textValue = String.valueOf((Float) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Double) {
                        textValue = String.valueOf((Double) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Long) {
                        cell.setCellValue((Long) value);
                    }
                    if (value instanceof Boolean) {
                        textValue = "是";
                        if (!(Boolean) value) {
                            textValue = "否";
                        }
                    } else if (value instanceof Date) {
                        textValue = sdf.format((Date) value);
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        if (value != null) {
                            textValue = value.toString();
                        }
                    }
                    if (textValue != null) {
                        matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            richString = new HSSFRichTextString(textValue);
                            cell.setCellValue(richString);
                        }
                    }
                }
            }

            workbook.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }finally {
            if(workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

复制代码

Guess you like

Origin juejin.im/post/7034804354792030215