easyexcel 3.0.x 版本实现指定列 锁定以及指定列隐藏

1:效果示例

2:代码示例:

复制代码
UnLockCell.java
java 复制代码
package com.example.juc.zhujie;

/**
 * @Author 
 * @Date Created in  2023/12/19 10:09
 * @DESCRIPTION:
 * @Version V1.0
 */

import java.lang.annotation.*;

/**
 * 用于标记锁定哪些列不需要锁定
 * @author 12926
 */
@Target(value = {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UnLockCell {


}

实例类:

java 复制代码
package com.example.juc.studyExcel.entity;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.example.juc.zhujie.UnLockCell;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author x
 * @Date Created in  2023/12/6 8:31
 * @DESCRIPTION:
 * @Version V1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {

    @ExcelProperty("用户id")
    @UnLockCell
    private String id;

    @ExcelProperty("姓名")
    private String name;

    @ExcelProperty("年龄")
    @ColumnWidth(5)
    private String age;
}

controller层:

java 复制代码
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.example.juc.studyExcel.entity.Student;
import com.example.juc.test.handler.CellHandler;
import com.example.juc.test.handler.LockSheetWriteHandler;
import com.example.juc.test.handler.StyleWriteHandler;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author 
 * @Date Created in  2023/12/16 16:32
 * @DESCRIPTION:
 * @Version V1.0
 */
@RestController
@RequestMapping("testSuoding")
public class 测试excel列锁定 {
    /**
     * 文件下载(失败了会返回一个有部分数据的Excel)
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link }
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写,这里注意,finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        List<Student> list = new ArrayList<>();
        list.add(new Student("1","夏天","18"));
        list.add(new Student("2","夏天","18"));
        list.add(new Student("3","夏天","18"));
        list.add(new Student("4","夏天","18"));
        list.add(new Student("5","夏天","18"));
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(),Student.class)
                .registerWriteHandler(new LockSheetWriteHandler())  //锁整张sheet
                .registerWriteHandler(new CellHandler(1))  //根据自定义注解解锁某些特定的列
                .sheet("模板")
                .doWrite(list);
    }
}
复制代码
LockSheetWriteHandler.java
java 复制代码
package com.example.juc.test.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;

import java.util.UUID;

/**
 * @author 夏
 * @since 2024/1/12 16:08
 */
public class LockSheetWriteHandler implements SheetWriteHandler {

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        //锁定工作簿,设置保护密码
        String passWord = UUID.randomUUID().toString();
        sheet.protectSheet(passWord);
        // 锁定单元格不可选中(防止别人直接复制内容到其他excel修改)
        ((SXSSFSheet) writeSheetHolder.getSheet()).lockSelectLockedCells(true);
    }
}
复制代码
CellHandler.java
java 复制代码
package com.example.juc.test.handler;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.example.juc.zhujie.UnLockCell;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author xlj
 * @Date Created in  2023/12/19 10:11
 * @DESCRIPTION:
 * @Version V1.0
 */
public class CellHandler implements CellWriteHandler {

    private static final String PASSWORD = "1qaz!QAZ";

    private static final Integer A = 1;
    private static final Integer B = 0;

    private final Integer bigData;
    public CellHandler(int i) {
        this.bigData = i;
    }

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
    }
    @Override
    public int order() {
        return Integer.MAX_VALUE;
    }
    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) {
            return; // 不处理表头
        }

        String fieldName = head.getFieldName();
        Class<?> clazz = writeSheetHolder.getClazz();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals(fieldName)) {
                if (field.isAnnotationPresent(UnLockCell.class) && field.isAnnotationPresent(ExcelProperty.class)) {
                    Map<String, Object> properties = new HashMap<>(1);
                    properties.put(CellUtil.LOCKED, false);
                    CellUtil.setCellStyleProperties(cell, properties);
                    Sheet sheet = writeSheetHolder.getSheet();
                    if (bigData == 1) {
                        sheet.setColumnHidden(A,true);
                    } else {
                        sheet.setColumnHidden(B,true);
                    }

                }
            }
        }
    }

}

注意:

pom依赖如下:

java 复制代码
      <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>

       <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.1</version>
        </dependency>
相关推荐
色空大师7 分钟前
23种设计模式
java·开发语言·设计模式
闲人一枚(学习中)8 分钟前
设计模式-创建型-建造者模式
java·设计模式·建造者模式
Bruce小鬼20 分钟前
QT文件基本操作
开发语言·qt
2202_7544215425 分钟前
生成MPSOC以及ZYNQ的启动文件BOOT.BIN的小软件
java·linux·开发语言
蓝染-惣右介28 分钟前
【MyBatisPlus·最新教程】包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段
java·数据库·tomcat·mybatis
小林想被监督学习29 分钟前
idea怎么打开两个窗口,运行两个项目
java·ide·intellij-idea
HoneyMoose31 分钟前
IDEA 2024.3 版本更新主要功能介绍
java·ide·intellij-idea
我只会发热32 分钟前
Java SE 与 Java EE:基础与进阶的探索之旅
java·开发语言·java-ee
是老余34 分钟前
本地可运行,jar包运行错误【解决实例】:通过IDEA的maven package打包多模块项目
java·maven·intellij-idea·jar
crazy_wsp34 分钟前
IDEA怎么定位java类所用maven依赖版本及引用位置
java·maven·intellij-idea