使用POI設置導出的EXCEL鎖定指定的單元格


注:要鎖定單元格需先為此表單設置保護密碼,設置之后此表單默認為所有單元格鎖定,可使用setLocked(false)為指定單元格設置不鎖定。

sheet.protectSheet("");//

 

    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(""); //設置表單保護密碼


            org.apache.poi.ss.usermodel.Row row = null;
            org.apache.poi.ss.usermodel.Cell cell = null;

            String cellValue = "132700002800";
            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();
        }
    }
    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM