我正在使用Apache POI来读写XSSF WorkBook .
点击一个按钮,需要生成一个文件(XSSF工作簿,其中包含5张,扩展名为.xlsm),其中有50列,其中我填充了4列....现在一旦保存了这个文件用户系统我的代码填充的这4列数据应该是不可编辑的(严格来说只有这4个,剩下的46列用户应该能够编辑数据) . 如何实现这一点??? (我可以使用最新的Apache POI)
您需要将单元格样式设置为锁定或解锁并保护工作表 . 锁定工作表将默认所有单元格为只读 .
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();
1 回答
您需要将单元格样式设置为锁定或解锁并保护工作表 . 锁定工作表将默认所有单元格为只读 .