I am using Apache POI to write data to an Excel file,and I want to make the first row readonly and the the other rows can be edit at any time.But I did not find an effective way to solve it.
Below is my code:
public static void createExcel(){
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet=workbook.createSheet("Variable");
CellStyle lockStyle=workbook.createCellStyle();
lockStyle.setLocked(true);
CellStyle unlockStyle=workbook.createCellStyle();
unlockStyle.setLocked(false);
sheet.protectSheet("www.hirain.com");
for(int i=0;i<=20;i++){
Row row=sheet.createRow(i);
if(i==0){
row.setRowStyle(lockStyle);
}else{
row.setRowStyle(unlockStyle);
}
Cell c1=row.createCell(0);
Cell c2=row.createCell(1);
c1.setCellValue((char)i);
c2.setCellValue(String.valueOf((char)(65+i)));
}
try {
OutputStream out=new FileOutputStream(new File("D:\\test.xls"));
workbook.write(out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("=========export excel success=========");
}
It seems this java code block should work,but in fact it will not only lock the first row but also lock the empty cells in other row.
So I want to know is there an effective way to only lock the first row of the excel file using apachepoi?