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

8

我正在使用Apache POI生成Excel模板,供客户下载,添加值并上传回来。

我想设置单元格的值为不可编辑,以便模板标题不能被编辑。

我尝试了这段代码,但它不起作用:

    cell.getCellStyle().setLocked(true)

我还读到过锁定Excel表格,然后允许列setlocked(false)会起作用,但我不确定客户会填写多少列,所以我希望除了我用Apache POI动态填充的那一列之外,所有其他列都可以编辑。
我希望我的问题清楚易懂。

https://dev59.com/Q2oy5IYBdhLWcg3wguWS - 2787184
2个回答

3

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

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. 

还可以将空字符串作为密码传递。这样,用户就不必输入密码来取消保护工作表。不要向该方法传递null,因为这会删除工作表保护。 - Matthias T

0

我不记得这个功能的效果如何——例如,我认为客户端可以使用菜单取消保护工作表——但是您确实需要通过类似于Sheet.protectSheet("")(没有密码,但仍然是受保护的工作表)来保护工作表。


这不完全是我需要的。:( - Dipendra Pokharel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接