小白的總結,大神勿噴;須要轉載請說明出處,若是有什麼問題,歡迎留言spa
1、需求:3d
一、某一列 、某一行或某些單元格不可編輯,其餘列能夠編輯code
2、期間遇到的問題blog
一、沒法設置成不可編輯get
二、設置爲不可編輯,導出後發現全部單元格均不可編輯;it
緣由:createCell();建立單元格後,單元格默認是鎖定狀態;protectSheet("密碼");保護工做表是保護全部鎖定的單元格;class
3、解決問題密碼
很少BB,直接上代碼im
HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("sheet名稱"); HSSFCellStyle lockstyle = wb.createCellStyle(); lockstyle.setLocked(true);//設置鎖定 lockstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); lockstyle.setFillForegroundColor(IndexedColors.RED.getIndex());//設置上鎖的單元格背景色 HSSFCellStyle unlockStyle=wb.createCellStyle(); unlockStyle.setLocked(false);//設置未鎖定 for(int i=0;i<10;i++){ HSSFRow row = sheet.createRow(i); for (int j = 0; j < 10; j++) { HSSFCell cell = row.createCell(j); cell.setCellStyle(unlockStyle);//默認是鎖定狀態;將全部單元格設置爲:未鎖定;而後再對須要上鎖的單元格單獨鎖定 if(j==1){//這裏能夠根據須要進行判斷;我這就將第2列上鎖了 cell.setCellStyle(lockstyle);//將須要上鎖的單元格進行鎖定 cell.setCellValue("上鎖了"); }else{ cell.setCellValue("沒上鎖了"); } } } //sheet添加保護,這個必定要不然光鎖定仍是能夠編輯的 sheet.protectSheet("123456"); FileOutputStream os = new FileOutputStream("D:\\workbook.xls"); wb.write(os); os.close();
四:結果
總結