Home » excel » java – Make column read-only using apache poi

java – Make column read-only using apache poi

Posted by: admin March 9, 2020 Leave a comment

Questions:

I am using apache-poi for generating the excel file. I need to make the 4th column read-only and the remaining 2 columns will be editable by the user.

I am using XSSFCellStyle to achieve this but it’s not working for me.

The entire code is:

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);
How to&Answers:

You have to protect the whole sheet and unlock the cells which should be editable:

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();

Answer:

CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
        DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(new String[] { "ReadOnlyCell" });
        HSSFDataValidation dataValidation = new HSSFDataValidation(addressList, dvConstraint);
    dataValidation.setSuppressDropDownArrow(true);

    dataValidation.setEmptyCellAllowed(false);
    dataValidation.createErrorBox("Error", "Cell can not be editable");
    spreadsheet.addValidationData(dataValidation);