poi锁定单元格

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即可。

"当你的才华还配不上你的野心的时候,就静下来努力,好好想想你到底花了多少精力在你想做的那件事上。"

原文地址:https://www.cnblogs.com/yanggb/p/13227630.html