easypoi多级表头多个sheet导出,动态导出列

Posted 符华-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了easypoi多级表头多个sheet导出,动态导出列相关的知识,希望对你有一定的参考价值。

一、多级表头和多个sheet

🧐 效果

因为这里是用注解实现的,只有到三级表头,如果表头超过了三级,比如有四级、五级的话,就不建议用注解,还是用模板比较方便。

🍔 代码

多级表头一个是可以用注解实现:@ExcelCollection 和 @Excel 组合使用还有就是可以用模板实现;还有一种就是用原生poi写,这个就更麻烦了。模板实现就更灵活,很复杂的表格都可以实现,不过就是填充数据比较麻烦。这里先写用注解实现的方式。

1、实体bean

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import lombok.Data;

import java.util.List;

@Data
public class ExcelExportVo 
	
	// 这两个就是一级表头,最后一级表头对应的是具体的某个属性,它们都是被包裹在一级表头下的
    @ExcelCollection(name = "用户信息")
    private List<UserInfo> userInfoList;

    @ExcelCollection(name = "用户角色和权限")
    private List<RoleInfo> roleInfoList;

    /**
     * 用户信息
     */
    @Data
    public static class UserInfo
    	// 二级表头可以用 groupName 实现
        @Excel(name = "用户账号",width = 20,groupName = "基本信息")
        private String userName;

        @Excel(name = "用户姓名",width = 20,groupName = "基本信息")
        private String realName;

        @Excel(name = "手机号码",width = 20,groupName = "基本信息")
        private String phone;

        @Excel(name = "所在公司",width = 20,groupName = "单位部门")
        private String com;

        @Excel(name = "所在部门",width = 20,groupName = "单位部门")
        private String dept;

        public UserInfo(String userName, String realName, String phone, String com, String dept) 
            this.userName = userName;
            this.realName = realName;
            this.phone = phone;
            this.com = com;
            this.dept = dept;
        
    

    /**
     * 用户角色权限
     */
    @Data
    public static class RoleInfo
        @Excel(name = "所属角色名称",width = 20,groupName = "角色")
        private String roleName;

        @Excel(name = "所属角色代码",width = 20,groupName = "角色")
        private String roleCode;

        @Excel(name = "菜单权限",width = 40,groupName = "权限")
        private String menu;

        @Excel(name = "数据权限",width = 40,groupName = "权限")
        private String data;

        public RoleInfo(String roleName, String roleCode, String menu, String data) 
            this.roleName = roleName;
            this.roleCode = roleCode;
            this.menu = menu;
            this.data = data;
        
    

2、ExcelUtil、ExcelStyleUtil

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.excel.imports.ExcelImportService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;

/**
 * excel操作工具类
 */
public class ExcelUtil 

    /**
     * 偶数行设置背景色
     */
    private static void setRowBackground(Workbook workbook)
        Sheet sheet = workbook.getSheetAt(0);
        CellStyle styles = ExcelStyleUtil.getStyles(workbook,false,(short) 12);
        for(int i = 0; i <= sheet.getLastRowNum(); i ++) 
            Row row = sheet.getRow(i);
            if (i%2==0)
                for(int j = 0; j < row.getPhysicalNumberOfCells(); j ++) 
                    Cell cell = row.getCell(j);
                    cell.setCellStyle(styles);
                
            
        
    

    /**
     * 导出设置隔行背景色
     * @param params 导出参数
     * @param list 数据
     * @param pojoClass pojo类型
     * @param fileName 文件名称
     * @param isSetRowBackground 是否设置隔行背景色
     */
    public static void exportExcel(ExportParams params, List<?> list, Class<?> pojoClass, String fileName,boolean isSetRowBackground, HttpServletResponse response)
        Workbook workbook = ExcelExportUtil.exportExcel(params,pojoClass,list);
        if (workbook != null);
        if (isSetRowBackground) setRowBackground(workbook);
        downLoadExcel(fileName, response, workbook);
    

    /**
     * excel 导出
     * @param list           数据
     * @param title          标题
     * @param sheetName      sheet名称
     * @param pojoClass      pojo类型
     * @param fileName       文件名称
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response)
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setStyle(ExcelStyleUtil.class);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    

    /**
     * excel 导出
     * @param list           数据
     * @param pojoClass      pojo类型
     * @param fileName       文件名称
     */
    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response)
        ExportParams exportParams = new ExportParams();
        exportParams.setStyle(ExcelStyleUtil.class);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    

    /**
     * list map 导出
     * @param list     数据
     * @param fileName 文件名称
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response)
        ExportParams exportParams = new ExportParams();
        exportParams.setStyle(ExcelStyleUtil.class);
        defaultExport(list, fileName, response);
    

    /**
     * 默认的 excel 导出
     * @param list         数据
     * @param pojoClass    pojo类型
     * @param fileName     文件名称
     * @param exportParams 导出参数
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams)
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    

    /**
     * 默认的 excel 导出
     * @param list     数据
     * @param fileName 文件名称
     */
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response)
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.XSSF);
        downLoadExcel(fileName, response, workbook);
    

    /**
     * 下载
     * @param fileName 文件名称
     * @param response
     * @param workbook excel数据
     */
    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook)
        try 
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLS.getValue(), "UTF-8"));
            workbook.write(response.getOutputStream());
         catch (IOException e) 
            e.printStackTrace();
        
    


    /**
     * excel 导入
     * @param filePath   excel文件路径
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     */
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException 
        if (StringUtils.isBlank(filePath)) 
            return null;
        
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setNeedSave(true);
        params.setSaveUrl("/excel/");
        try 
            return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
         catch (NoSuchElementException e) 
            throw new IOException("模板不能为空");
         catch (Exception e) 
            throw new IOException(e.getMessage());
        
    

    /**
     * excel 导入
     * @param file       上传的文件
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param needVerify 是否检验excel内容
     * @param pojoClass  pojo类型
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerify, Class<T> pojoClass) throws IOException 
        if (file == null) 
            return null;
        
        try 
            return importExcel(file.getInputStream(), titleRows, headerRows, needVerify, pojoClass);
         catch (Exception e) 
            throw new IOException(e.getMessage());
        
    

    /**
     * excel 导入
     * @param inputStream 文件输入流
     * @param titleRows   标题行
     * @param headerRows  表头行
     * @param needVerify  是否检验excel内容
     * @param pojoClass   pojo类型
     */
    public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerify, Class<T> pojoClass) throws IOException 
        if (inputStream == null) 
            return null;
        
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("upload/excel/");
        params.setNeedSave(true);
        params.setNeedVerify(needVerify);
        try 
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
         catch (NoSuchElementException e) 
            throw new IOException("excel文件不能为空");
         catch (Exception e) 
            throw new IOException(e.getMessage());
        
    

    /**
     * Excel 类型枚举
     */
    enum ExcelTypeEnum 
        XLS("xls"), XLSX("xlsx");
        private String value;

        ExcelTypeEnum(String value) 
            this.value = value;
        

        public String getValue() 
            return value;
        

        public void setValue(String value) 
            this.value = value;
        
    


    /**
     * 上传文件,返回一个workbook
     * @param file
     */
    public static Workbook importExcel(MultipartFile file) throws IOException 
        File toFile = new File(file.getOriginalFilename());
        Workbook workbook = null;
        if(toFile.getPath().endsWith("xls"))
            workbook = new HSSFWorkbook(file.getInputStream());
        else if(toFile.getPath().endsWith("xlsx"))
            workbook = new XSSFWorkbook(file.getInputStream());
        else 
            throw new RuntimeException("请确认你上传的文件类型");
        
        return workbook;
    

    /**
     * 读取指定sheet的数据
     * @param file 上传的文件
     * @param sheetName 要读取的sheetName
     * @param titleRows 表头行数
     * @param headRows 标题行数
     * @param startRows 表头之前有多少行不要的数据,从1开始,忽略空行
     * @param readRows 要读取多少行数据,从0开始,比如读取十行,值就是9; 不指定时默认为0
     * @param pojoClass 实体
     */
    public static <T> List<T> importExcel(MultipartFile fileeasypoi导出单个sheet和多个sheet

使用easypoi根据表头信息动态导出excel

easypoi导出word表格怎么遍历数据

easypoiword导出图片发现无法读取的内容

使用easypoi时,动态设置excel列宽

java集成poi报表,导出xlsxlsx,表头,内容,sheet动态数据填充,局部单元格颜色字体设置