生成excel文件(有备注和表头的情况)

要使用 Java 导出 Excel 文件,并且通过 @ExcelProperty 注解进行列的映射,可以利用 EasyExcel 库。EasyExcel 是阿里巴巴开源的一款高性能 Excel 读写工具,它支持通过注解将类与 Excel 的列进行映射,简化了 Excel 操作的复杂性。

前提准备

  • 添加 EasyExcel 依赖到 pom.xml 文件中:

    <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.1.0</version> </dependency>

Excel 导出实现

  1. 定义导出数据的 Java 类 首先,需要定义一个类来映射 Excel 表格中的每一列。

    import com.alibaba.excel.annotation.ExcelProperty;
    import com.alibaba.excel.annotation.WriteStyle;

    import java.io.Serializable;

    public class EmployeeExcel implements Serializable {

     // 第一行备注信息
     @ExcelProperty("工号")
     private String employeeId;  // 工号(6位文本)
    
     @ExcelProperty("姓名")
     private String name;
    
     @ExcelProperty("操作类型")
     private String operationType;
    
     @ExcelProperty("部门全称")
     private String departmentName;
    
     @ExcelProperty("汇报上级")
     private String supervisor;
    
     @ExcelProperty("工作城市")
     private String workCity;
    
     @ExcelProperty("社保城市")
     private String socialSecurityCity;
    
     @ExcelProperty("职位全称")
     private String positionTitle;
    
     @ExcelProperty("HC编码")
     private String hcCode;
    
     @ExcelProperty("群组")
     private String group;
    
     @ExcelProperty("一级部门")
     private String firstLevelDepartment;
    
     @ExcelProperty("二级部门")
     private String secondLevelDepartment;
    
     @ExcelProperty("三级部门")
     private String thirdLevelDepartment;
    
     @ExcelProperty("四级部门")
     private String fourthLevelDepartment;
    
     @ExcelProperty("五级部门")
     private String fifthLevelDepartment;
    
     @ExcelProperty("六级部门")
     private String sixthLevelDepartment;
    
     @ExcelProperty("七级部门")
     private String seventhLevelDepartment;
    
     @ExcelProperty("汇报上级工号")
     private String supervisorEmployeeId;
    
     @ExcelProperty("汇报上级姓名")
     private String supervisorName;
    
     @ExcelProperty("工作城市")
     private String workCity2;  // 注意列名可以重复,需要做区分
    
     @ExcelProperty("社保城市(无需填写)")
     private String socialSecurityCity2;
    
     @ExcelProperty("岗位ID编号")
     private String positionId;
    
     @ExcelProperty("是否带编调整")
     private String isAdjustment;
    
     @ExcelProperty("HC编码(非带编调整则该项是必填)")
     private String hcCodeForAdjustment;
    
     @ExcelProperty("校验未通过原因")
     private String validationFailureReason;
    
     // Getter and Setter methods
     public String getEmployeeId() {
         return employeeId;
     }
    
     public void setEmployeeId(String employeeId) {
         this.employeeId = employeeId;
     }
    
     // 其他字段的 Getter 和 Setter 方法
    

    }

  2. 使用 EasyExcel 导出数据 然后,可以利用 EasyExcel 库来导出数据。接下来是 Excel 导出的核心代码。

    import com.alibaba.excel.EasyExcel;
    import com.alibaba.excel.write.builder.ExcelWriterBuilder;
    import com.alibaba.excel.write.style.AbstractCellStyleStrategy;
    import com.alibaba.excel.write.style.FillPatternType;
    import com.alibaba.excel.write.style.HorizontalAlignmentStyleStrategy;
    import org.apache.poi.ss.usermodel.*;

    import java.util.ArrayList;
    import java.util.List;

    public class ExcelExportExample {

     public static void main(String[] args) {
         // 数据列表
         List<EmployeeExcel> employeeExcelList = new ArrayList<>();
         
         // 模拟添加数据
         EmployeeExcel employee = new EmployeeExcel();
         employee.setEmployeeId("123456");
         employee.setName("张三");
         employee.setOperationType("新增");
         // 填充其他字段...
         
         employeeExcelList.add(employee);
    
         // 导出 Excel 文件
         exportExcel(employeeExcelList);
     }
    
     public static void exportExcel(List<EmployeeExcel> data) {
         // Excel 文件路径
         String fileName = "员工信息.xlsx";
         
         // 创建 ExcelWriter
         EasyExcel.write(fileName, EmployeeExcel.class)
                 .sheet("员工信息")
                 .doWrite(data);
     }
    

    }

  3. 添加备注信息 如果 Excel 的第一行是备注信息(如工号为6位文本格式等),可以在写入 Excel 时手动插入备注行。备注行可以通过自定义样式进行设置,如背景颜色。

  4. 设置单元格合并和背景颜色 如果需要合并单元格或者设置背景颜色,你可以使用 WriteStyleCellStyle 来设置样式。示例如下:

复制代码

java

import com.alibaba.excel.write.style.AbstractCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;

import java.util.List;

public class CustomCellStyleStrategy extends AbstractCellStyleStrategy {

    @Override
    protected void initCellStyle(Workbook workbook) {
        super.initCellStyle(workbook);
        // 设置备注行的背景颜色
        Sheet sheet = workbook.getSheetAt(0);
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("工号为6位文本格式");
        row.createCell(1).setCellValue("变更前信息(不用填写,系统自动填充)");

        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));

        // 设置背景颜色
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        row.getCell(0).setCellStyle(cellStyle);
        row.getCell(1).setCellStyle(cellStyle);
    }

    @Override
    protected void setColumnWidth(Sheet sheet) {
        super.setColumnWidth(sheet);
        sheet.setColumnWidth(0, 6000); // 设置列宽
    }
}

EasyExcel.write() 方法中加入该自定义样式:

EasyExcel.write(fileName, EmployeeExcel.class)
          .sheet("员工信息")
          .registerWriteHandler(new CustomCellStyleStrategy())
          .doWrite(data);

总结

  • @ExcelProperty 注解用于将 Java 类的字段映射到 Excel 的列。
  • 通过 EasyExcel,可以轻松实现 Excel 文件的导出,支持数据模型与表格列的直接绑定。
  • 在导出时,可以添加备注行、合并单元格、设置背景颜色等自定义样式。
相关推荐
非 白7 分钟前
【Java分布式】Nacos注册中心
java·开发语言·nacos·注册中心
吃海鲜的骆驼13 分钟前
服务异步通讯与RabbitMQ
java·分布式·后端·rabbitmq
羱滒16 分钟前
sql调优之数据库开发规范
java·数据库·数据库开发
Forget the Dream1 小时前
设计模式之责任链模式
java·c++·设计模式·责任链模式
jonyleek1 小时前
「JVS更新日志」低代码、企业会议、智能BI、智能排产2.26更新说明
java·大数据·低代码·数据分析·软件需求
计算机小白一个1 小时前
蓝桥杯 Java B 组之最短路径算法(Dijkstra、Floyd-Warshall)
java·数据结构·算法·蓝桥杯
曼岛_1 小时前
[密码学实战]Java实现SM4加解密(ecb,cbc)及工具验证
java·密码学
Forget the Dream2 小时前
设计模式之代理模式
java·c++·设计模式·代理模式
帅的飞起来2 小时前
设计模式--spring中用到的设计模式
java·spring·设计模式
張葒兵3 小时前
记一次命令行启动springboot项目的问题 java -jar的问题
java·spring boot·jar