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>
相关推荐
憨子周27 分钟前
2M的带宽怎么怎么设置tcp滑动窗口以及连接池
java·网络·网络协议·tcp/ip
霖雨2 小时前
使用Visual Studio Code 快速新建Net项目
java·ide·windows·vscode·编辑器
SRY122404192 小时前
javaSE面试题
java·开发语言·面试
Fiercezm2 小时前
JUC学习
java
无尽的大道3 小时前
Java 泛型详解:参数化类型的强大之处
java·开发语言
ZIM学编程3 小时前
Java基础Day-Sixteen
java·开发语言·windows
我不是星海3 小时前
1.集合体系补充(1)
java·数据结构
放逐者-保持本心,方可放逐3 小时前
react 组件应用
开发语言·前端·javascript·react.js·前端框架
P.H. Infinity3 小时前
【RabbitMQ】07-业务幂等处理
java·rabbitmq·java-rabbitmq
爱吃土豆的程序员3 小时前
java XMLStreamConstants.CDATA 无法识别 <![CDATA[]]>
xml·java·cdata