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>