使用apache poi将列设为只读

sim*_*u94 6 java excel apache-poi

我正在使用apache-poi生成excel文件.我需要将第4列设为只读,其余2列将由用户编辑.

我正在用它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);
Run Code Online (Sandbox Code Playgroud)

Kai*_*Kai 13

您必须保护整个工作表并解锁应该可编辑的单元格:

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();
Run Code Online (Sandbox Code Playgroud)

  • @AM:在正常的例子中,你可以按照 Kai 的做法。但是,当您还想使用 lockAutoFilter 和 lockFormatColumns 格式化工作表时,它们应该在执行 protectedSheet 调用之前进行。(很难在纯文本注释中实现可视化;-))换句话说:在protectSheet之前执行所有操作,并且仅在projectSheet之后解锁单元格。 (2认同)