2011-12-14 114 views
5

我使用apache-poi來生成excel文件。我需要將第4列設置爲只讀,其餘2列可以由用戶編輯。使用apache poi創建列只讀

我使用XSSFCellStyle來達到這個目標,但它不適合我。

整個代碼爲:

Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>(); 

XSSFCellStyle style5 = wb.createCellStyle(); 
XSSFFont headerFont = wb.createFont(); 
headerFont.setBold(true); 
style5.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); 
style5.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); 
style5.setFont(headerFont); 
style5.setLocked(true); // this line does not get executed. 
styles.put("header", style5); 
+0

你是什麼意思時,你說行不沒有得到執行?你有例外嗎? – Pieter 2011-12-14 10:00:52

回答

12

你必須保護整個片和解鎖應該是可編輯的細胞:

String file = "c:\\poitest.xlsx"; 
FileOutputStream outputStream = new FileOutputStream(file); 
Workbook wb = new XSSFWorkbook(); 

CellStyle unlockedCellStyle = wb.createCellStyle(); 
unlockedCellStyle.setLocked(false); 

Sheet sheet = wb.createSheet(); 
sheet.protectSheet("password"); 
Row row = sheet.createRow(0); 
Cell cell = row.createCell(0); 
cell.setCellValue("TEST"); 
cell.setCellStyle(unlockedCellStyle); 

wb.write(outputStream); 
outputStream.close();