使用 Apache POI 在 Excel 中锁定单列 [英] Lock single column in Excel using Apache POI

查看:75
本文介绍了使用 Apache POI 在 Excel 中锁定单列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 Excel,其中只有特定的列被锁定(只读),其余的都是可编辑的,

I want to create a Excel in which only a specific column is locked(Read-only), and the rest are editable,

我正在使用以下方法,但这似乎不起作用.

I am using the following approach, but that doesn't seem to work.

创建两个 CellStyle,一个使用 setLocked(true),另一个使用 setLocked(false).

Create two CellStyles, one with setLocked(true) and other with setLocked(false).

然后对需要锁定的列中的所有单元格应用锁定样式,对所有其他单元格应用未锁定样式.

Then apply the locked style for all the cells in the column which needs to be locked, and the unlocked style for all the other cells.

使用 sheet.protectSheet("") 保护工作表;

Protect the sheet using sheet.protectSheet("");

但是当我在 open office 打开创建的 Excel 时,我发现所有的单元格都被锁定了!

But when I open the created Excel in open office, I notice that all the cells are locked!

它们都不可编辑.

如何才能达到上述要求?

How can I achieve the above requirement?

P.S:我不能使用数据验证方法.

P.S : I cant use the data validation approach.

推荐答案

如果你反其道而行之.保护整个工作表并为应该可编辑的单元格调用 setLocked(false).

If you do the opposite it works. Protect the whole sheet and call setLocked(false) for 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();

这篇关于使用 Apache POI 在 Excel 中锁定单列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆