生成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 文件的导出,支持数据模型与表格列的直接绑定。
  • 在导出时,可以添加备注行、合并单元格、设置背景颜色等自定义样式。
相关推荐
六千江山16 分钟前
从字符串中提取符合规则的汽车车牌
java
33255_40857_2805925 分钟前
从韩立结婴看Java进阶:一个10年老码农的修仙式成长指南
java
赵星星52025 分钟前
透彻理解Java中的深拷贝与浅拷贝:从误区到最佳实践
java·后端
心月狐的流火号27 分钟前
Java CompletableFuture 核心API
java
黑客影儿37 分钟前
Java技术总监的成长之路(技术干货分享)
java·jvm·后端·程序人生·spring·tomcat·maven
京东云开发者42 分钟前
EXCEL导入—设计与思考
java·架构
Warren981 小时前
软件测试-Selenium学习笔记
java·javascript·笔记·学习·selenium·测试工具·安全
没有bug.的程序员1 小时前
JVM 运行时数据区详解:内存模型与对象生命周期全景解析
java·jvm·运行时数据区·内存模型·对象生命周期
一语长情2 小时前
Netty流量整形:保障微服务通信稳定性的关键策略
java·后端·架构
盖世英雄酱581362 小时前
第一个RAG项目遇到的问题
java·spring boot