sheet 名称 POI java 的锁定重命名

lock rename of sheet name POI java

sheet 名称 POI 的锁定重命名 java

如何保护 sheet 名称不让用户更改它

XSSFSheet sheet = ((XSSFSheet)s);
//to lock my sheet name
    sheet.lockmysheetName();

我只想保护sheet名字。

Microsoft Excel 不在 sheet 级别上提供对 sheet 名称的锁定。有可能protect a workbook。这样可以保护工作簿的结构。这包括 sheet 名称的锁定,也包括 sheets 订单的锁定和插入新 sheets.

的锁定

这是XSSFWorkbook.lockStructure设置的。

HSSFWorkbook 到目前为止没有可比性。但是使用 InternalWorkbookWorkbookRecordList 以及有关二进制 *.xls 工作簿中的二进制记录流的知识,可以实现相同的目的。

完整示例:

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.ProtectRecord;
import org.apache.poi.hssf.model.InternalWorkbook;
import org.apache.poi.hssf.model.WorkbookRecordList;

public class CreateExcelLockStructure {
    
 static void lockStructure(HSSFWorkbook hssfWorkbook) {
  InternalWorkbook internalWorkbook = hssfWorkbook.getInternalWorkbook();
  WorkbookRecordList workbookRecordList = internalWorkbook.getWorkbookRecordList();
  int protpos = workbookRecordList.getProtpos();
  Record record = workbookRecordList.get(protpos);
  if (record instanceof ProtectRecord) {
   ProtectRecord protectRecord = (ProtectRecord)record;
   protectRecord.setProtect(true);
  } else {
   ProtectRecord protectRecord = new ProtectRecord(true);
   protpos = workbookRecordList.size() - 1;
   workbookRecordList.add(protpos, protectRecord);
   workbookRecordList.setProtpos(protpos);
  }
 }

 public static void main(String[] args) throws Exception {
     
  Workbook workbook = new XSSFWorkbook(); String filePath = "./CreateExcelLockStructure.xlsx";
  //Workbook workbook = new HSSFWorkbook(); String filePath = "./CreateExcelLockStructure.xls";

  Sheet sheet = workbook.createSheet("SheetName1");
  sheet = workbook.createSheet("SheetName2");

  if (workbook instanceof XSSFWorkbook) {
   XSSFWorkbook xssfWorkbook = (XSSFWorkbook)workbook;   
   xssfWorkbook.lockStructure();
  } else if (workbook instanceof HSSFWorkbook) {
   HSSFWorkbook hssfWorkbook = (HSSFWorkbook)workbook;
   lockStructure(hssfWorkbook);
  }

  FileOutputStream out = new FileOutputStream(filePath);
  workbook.write(out);
  out.close();
  workbook.close();

 }

}