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>
相关推荐
好开心332 分钟前
axios的使用
开发语言·前端·javascript·前端框架·html
又蓝25 分钟前
使用 Python 操作 Excel 表格
开发语言·python·excel
小灰灰要减肥25 分钟前
装饰者模式
java
张铁铁是个小胖子36 分钟前
MyBatis学习
java·学习·mybatis
余~~1853816280037 分钟前
稳定的碰一碰发视频、碰一碰矩阵源码技术开发,支持OEM
开发语言·人工智能·python·音视频
Am心若依旧4091 小时前
[c++11(二)]Lambda表达式和Function包装器及bind函数
开发语言·c++
明月看潮生1 小时前
青少年编程与数学 02-004 Go语言Web编程 20课题、单元测试
开发语言·青少年编程·单元测试·编程与数学·goweb
Yan.love1 小时前
开发场景中Java 集合的最佳选择
java·数据结构·链表
椰椰椰耶1 小时前
【文档搜索引擎】搜索模块的完整实现
java·搜索引擎
大G哥1 小时前
java提高正则处理效率
java·开发语言