easyExcel导出 无模版 实体类 导出 自定义表头

喜欢的点赞 不喜欢的解散 创作不易记得三连

开整

1 导入依赖

 <!--导出数据-->
<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>easyexcel</artifactId>
     <version>2.1.3</version>
 </dependency>

2.样式工具类`

import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;

/**
 * excel 样式工具类
 * @author MC
 * @date 2020/12/17 19:08
 */
public class CellStyleUtil {
     

    /**
     * excel首列序号列样式
     * @param workbook
     * @return
     */
    public static CellStyle firstCellStyle(Workbook workbook) {
     
        CellStyle cellStyle = workbook.createCellStyle();
        //居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
        //设置边框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        //文字
        Font font = workbook.createFont();
        font.setBold(Boolean.TRUE);
        cellStyle.setFont(font);
        return cellStyle;
    }

    /**
     * 用于设置excel导出时的样式
     * easyexcel 导出样式
     * @return
     */
    public static HorizontalCellStyleStrategy getHorizontalCellStyleStrategy() {
     
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为红色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short)12);
        headWriteCellStyle.setWriteFont(headWriteFont);
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 背景绿色
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //边框
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        //文字
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short)12);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }

}

3 表头字段设置 自定义在这里操作

3.1 查询表信息 mapper

/**
     * 查询表字段信息
     * @param tableName
     * @return
     */
    @Select("select DISTINCT COLUMN_NAME,DATA_TYPE from information_schema.COLUMNS where table_name = #{tableName}")
    List<Map> listTableColumn(String tableName);
/**
     * 查询表 有哪些字段
     * @param tableName
     * @return
     */
    private List<Map> getAllFiled(String tableName){
     
         return iStandingBookMangerService.listTableColumn(tableName);
    }
	/**
     * 处理表信息
     * @param tableName 
     * @return
     */
    private List<List<String>> getMorningCheckHeadFiled(String tableName){
     
        List<List<String>> list = new ArrayList<>();
        List<Map> allFiled = getAllFiled(tableName);
        for (Map map : allFiled) {
     
            String column_name = map.get("COLUMN_NAME").toString();
            List<String> list1 = new ArrayList<>();
            list1.add(column_name);
            list.add(list1);
        }
        return list;
    }

4.处理查回来的 map 数据 根据表头 动态匹配数据

public List<List<Object>> getData(List<Map<Object, Object>> allDataByTableName, String tableName) throws Exception {
     
        List<Map> allFiled = getAllFiled(tableName);
        List<List<Object>>  result= new ArrayList(allDataByTableName.size());
        List<String> list1 = new ArrayList<>();
        for (Map map : allFiled) {
     
            String column_name = map.get("COLUMN_NAME").toString();
            list1.add(column_name);
        }
        for (int i =0;i<allDataByTableName.size();i++) {
     
            Map<Object, Object> temp = allDataByTableName.get(i);
            List<Object> list = new ArrayList<>();
            for (String s : list1) {
     
                Object o = temp.get(s);
                list.add(o);
            }
            result.add(list);
        }
        return result;
    }

5 .测试走一波

@PostMapping("/exportStandingBook")
    @ApiOperation(value = "导出台帐")
    public void exportStanding(@RequestBody JSONObject param,@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response) throws Exception {
     
        String tableName = param.getString("tableName");
        List<Map<Object, Object>> allDataByTableName = iStandingBookMangerService.getAllDataByTableName(tableName);
        List<List<Object>> data = getData(allDataByTableName);
        List<List<String>> morningCheckHeadFiled = getMorningCheckHeadFiled(allDataByTableName);
        try {
     
            response.setCharacterEncoding("utf-8");
            //mime类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Content-disposition", "attachment;filename=" + ".xlsx");
            // 这里 URLEncoder.encode可以防止中文乱码 当然和 easyExcel没有关系
            // 设置文件名
            String fileName = URLEncoder.encode("元素列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream())
                    .head(morningCheckHeadFiled)
                    .registerWriteHandler(CellStyleUtil.getHorizontalCellStyleStrategy())
                    .registerWriteHandler(new CustomRowWriteHandler())
                    // 设置 sheet
                    .autoCloseStream(Boolean.FALSE).sheet("用户")
                    //自定义方法输出样式设置。可以不写,就默认缺省。
                    //自定义注解excel单元格样式,在字段上注解。
                    //自定义注解
                    .doWrite(data);
        } catch (Exception e) {
     
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>(8);
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

6.postman测试

easyExcel导出 无模版 实体类 导出 自定义表头_第1张图片

7 结果

easyExcel导出 无模版 实体类 导出 自定义表头_第2张图片

你可能感兴趣的:(工具介绍)