poi中提供了一個Sheet.protectSheet()方法用於設置表單保護密碼和一個XSSFCellStyle.setLocked()方法用於設置單元格是否使用表單保護密碼進行鎖定,將兩者配合使用就可以達到鎖定單元格的效果。
public static void WriteExcelByPoi(String fileData) throws IOException, InvalidFormatException { try { InputStream in = new FileInputStream(fileData); Workbook workbook = new XSSFWorkbook(in); org.apache.poi.ss.usermodel.Sheet sheet = (org.apache.poi.ss.usermodel.Sheet)workbook.getSheetAt(1); sheet.protectSheet("yanggb"); // 設置表單保護密碼 org.apache.poi.ss.usermodel.Row row = null; org.apache.poi.ss.usermodel.Cell cell = null; String cellValue = "1234567890"; XSSFCellStyle alterableStyle = (XSSFCellStyle)workbook.createCellStyle(); // 獲取當前單元格的樣式對象 alterableStyle.setLocked(true); // 設定此單元格為鎖定狀態 XSSFCellStyle nolockedStyle = (XSSFCellStyle)workbook.createCellStyle(); // 獲取當前單元格的樣式對象 nolockedStyle.setLocked(false); // 設定此單元格為非鎖定狀態 String value = "非鎖定"; for (int i = 0; i < 5; i++) { System.out.println(" i =" + i); row = sheet.createRow(i); cell = row.createCell(0); cell.setCellValue(cellValue); cell.setCellStyle(alterableStyle); cell = row.createCell(1); cell.setCellValue(value); cell.setCellStyle(nolockedStyle); } in.close(); FileOutputStream out = null; try { out = new FileOutputStream(fileData); workbook.write(out); } catch (IOException e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
要注意的是,如果單獨設置了表單保護密碼或設置單元格使用表單密碼鎖定都不能達到想要的效果。
而如果想要部分單元格鎖定的話,通過setLocked(boolean isLocked)的參數設置true或false即可。
"當你的才華還配不上你的野心的時候,就靜下來努力,好好想想你到底花了多少精力在你想做的那件事上。"