首页 文章

Apache POI - Excel写入 - 锁定单个单元格

提问于
浏览
8

我正在使用Apache POI生成我的客户可以下载的Exccel Templete,添加值并上传回来 .

我想将单元格值设置为不可编辑,以便无法编辑模板 Headers .

我试过这段代码,但它不起作用,

cell.getCellStyle().setLocked(true)

我还读到锁定excel表然后允许列setlocked(false)可以工作,但我不确定客户端将填充多少列,所以我想要编辑所有其他列,除了我填写的列动态地使用Apache POI .

我希望我的查询清楚明白 .

2 回答

  • 2

    尝试以下代码,它可以解决您的问题:

    HSSFWorkbook workbook = new XSSFWorkbook(); 
    
    // Cell styles. Note the setLocked(true) method call. 
    HSSFCellStyle lockedNumericStyle = workbook.createCellStyle(); 
    lockedNumericStyle.setAlignment(XSSFCellStyle.ALIGN_RIGHT); 
    lockedNumericStyle.setLocked(true); 
    
    HSSFSheet sheet = workbook.createSheet("Protection Test"); 
    HSSFRow row = sheet.createRow(0); 
    HSSFCell cell = row.createCell(0); 
    cell.setCellValue(100); 
    cell.setCellStyle(lockedNumericStyle); 
    
    // This line should cause all locked cells to be protected, 
    // the user should not be able to change the cells 
    // contents. 
    sheet.protectSheet("password"); 
    
    The password makes it possible to remove the protection from the sheet and makes it possible then for the locked cells to be modified.
    
  • 0

    我不记得这有多好用 - 例如,我认为客户端可以使用菜单取消保护工作表 - 但你需要通过类似Sheet.protectSheet("")(无密码,但仍然是受保护的工作表)来保护工作表 . )

相关问题