0

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 ?

Community
  • 1
  • 1
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • Check This http://stackoverflow.com/a/17938583/624003 – Sankumarsingh Jan 15 '15 at 12:17
  • @Sankumarsingh http://stackoverflow.com/questions/17932575/apache-poi-locking-header-rows/17938583#17938583 is useless for me,what I want to do it lock the specified rows to prevent any user edit it.Freeze and lock are two different things. – flyingfox Jan 16 '15 at 09:55
  • @lucumt FYI, `lockStyle.setLocked(true);` protects whole Excel sheet not a single row/column. – Chandra Shekhar Aug 23 '16 at 12:00

1 Answers1

0

its work for me

                if(y==0) {
                    unlockedCellStyle.setLocked(true);
                    sheet.lockFormatCells(true);
                    sheet.enableLocking();
                }else {
                    unlockedCellStyle.setLocked(false);
                    sheet.lockFormatCells(false);
                    sheet.enableLocking();
                }
                cell.setCellStyle(unlockedCellStyle);
david
  • 1
  • 2