【问题标题】:How to Lock a particular cell in XSSF Work Book so user could not edit that如何锁定 XSSF 工作簿中的特定单元格,以便用户无法编辑该单元格
【发布时间】:2017-07-03 12:46:11
【问题描述】:

我正在使用 Apache POI 来读写 XSSF WorkBook。

单击按钮时,需要生成一个文件(其中包含 5 张工作表的 XSSF 工作簿,.xlsm 扩展名)它有 50 列,其中我要填充 4 列 .... 现在一旦这个文件保存在用户系统中我的代码填充的这 4 列数据应该是不可编辑的(严格来说只有这 4 列,其余 46 列用户应该能够编辑数据)。怎么实现??? (我可以使用最新的 Apache POI)

【问题讨论】:

    标签: apache apache-poi xssf


    【解决方案1】:

    您需要将单元格样式设置为锁定或解锁并保护工作表。锁定工作表将使所有单元格默认为只读。

    XSSFWorkbook workbook = new XSSFWorkbook(); 
    XSSFSheet sheet = (XSSFSheet)workbook.createSheet("worksheet");
    sheet.protectSheet("password");
    
    
    CellStyle lockedStyle = workbook.createCellStyle();
    lockedStyle.setLocked(true); 
    
    CellStyle defaultStyle = workbook.createCellStyle();
    defaultStyle.setLocked(false);
    
    // Create a header row
    Row row = sheet.createRow(0);    
    Cell cell = row.createCell(0);
    cell.setCellValue("locked");
    cell.setCellStyle(lockedStyle);
    sheet.autoSizeColumn(0);
    
    cell = row.createCell(1);
    cell.setCellValue("this cell unlocked");
    cell.setCellStyle(defaultStyle);
    sheet.autoSizeColumn(1);
    
    cell = row.createCell(2);
    cell.setCellValue("this column unlocked");
    cell.setCellStyle(defaultStyle);
    sheet.autoSizeColumn(2);
    
    // sets any auto-generated cells in this column to unlocked
    sheet.setDefaultColumnStyle(2, defaultStyle);
    
    FileOutputStream fileOut =  new FileOutputStream("doc.xlsx");
    workbook.write(fileOut);
    
    workbook.close();
    fileOut.close();
    

    【讨论】:

      猜你喜欢
      • 2015-01-12
      • 1970-01-01
      • 2016-08-14
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 2022-08-04
      相关资源
      最近更新 更多