使excel表只读

我想使用Apache POI HSSF创build后只读Excel表。 我怎样才能做到这一点?

详细的描述可以在这里find: http : //systeminetwork.com/article/locking-cells-hssf

基本上你必须分配你的单元格与CellStyle.setLocked(true)自定义CellStyle.setLocked(true)

编辑

嗨Gaurav,这里是完整的工作代码:

 HSSFWorkbook workbook = new HSSFWorkbook();
 HSSFSheet sheet = workbook.createSheet(“sheet1”);
 / *密码所需的密码才能生效* /
 sheet.protectSheet( “secretPassword的”);

 / *单元格样式locking* /
 CellStyle lockedCellStyle = workbook.createCellStyle();
 lockedCellStyle.setLocked(真);
 / *可编辑单元格的单元格样式* /
 CellStyle unlockedCellStyle = workbook.createCellStyle();
 unlockedCellStyle.setLocked(假);

 / *将被locking的单元* /
 Cell lockedCell = sheet.createRow(0).createCell(0);
 lockedCell.setCellValue(“嗨,我被locking...”);
 lockedCell.setCellStyle(lockedCellStyle);

 / *解锁的单元格* /
 Cell unlockedCell = sheet.createRow(1).createCell(0);
 unlockedCell.setCellValue(“只编辑我...”);
 unlockedCell.setCellStyle(unlockedCellStyle);

 OutputStream out = new FileOutputStream(“sample.xls”);
 workbook.write(下);
了out.flush();
 out.close();

这里是一些testing代码,使特定的单元格只读 。 根据你在@Thomas Weber的回答中的评论。

这将在单元格中设置初始值,然后使用数据约束来确保用户不能在Excel中修改固定值。 试试看。

 HSSFWorkbook workBook = new HSSFWorkbook (); HSSFSheet sheet1 = workBook.createSheet(); HSSFRow row1 = sheet1.createRow(10); HSSFCell cell1 = row1.createCell(0); cell1.setCellValue("text: The new line which should be locked"); // SETTING INITIAL VALUE HSSFCell displayNameCell = cell1; String[] displayNameList = new String[]{"text: The new line which should be locked"}; //ADDING SAME VALUE INTO A STRING ARRAY AS THE RESTRICTED VALUE DVConstraint displayNameConstraint = DVConstraint.createExplicitListConstraint(displayNameList); CellRangeAddressList displayNameCellRange = new CellRangeAddressList(displayNameCell.getRowIndex(),displayNameCell.getRowIndex(),displayNameCell.getColumnIndex(),displayNameCell.getColumnIndex()); HSSFDataValidation displayNameValidation = new HSSFDataValidation(displayNameCellRange,displayNameConstraint); displayNameValidation.createErrorBox("Not Applicable","Cannot change the value"); displayNameValidation.setSuppressDropDownArrow(true); displayNameCell.getSheet().addValidationData(displayNameValidation); // Write the output to a file FileOutputStream fileOut1 = new FileOutputStream("D:\\book.xls"); workBook.write(fileOut1); fileOut1.close(); 

此代码基于此线程http://osdir.com/ml/user-poi.apache.org/2009-07/msg00056.html

 new File("/path/to/file.xls").setReadOnly();