如何锁定XSSF工作簿中的特定单元格,以便用户无法编辑该单元格

时间:2015-01-28 15:16:51

标签: apache apache-poi xssf

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

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

1 个答案:

答案 0 :(得分:0)

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

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();