制作excel表格只读

时间:2010-09-19 16:12:52

标签: java excel apache-poi

我想在使用Apache POI HSSF创建它之后只读excel表。我怎么能这样做?

3 个答案:

答案 0 :(得分:5)

详细说明可在此处找到: http://systeminetwork.com/article/locking-cells-hssf

基本上,您必须为自己的单元格指定CellStyle

的自定义{{1}}

被修改

嗨Gaurav, 这是完整且有效的代码:

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet1");
/* password required for locks to become effective */
sheet.protectSheet("secretPassword");

/* cell style for locking */
CellStyle lockedCellStyle = workbook.createCellStyle();
lockedCellStyle.setLocked(true);
/* cell style for editable cells */
CellStyle unlockedCellStyle = workbook.createCellStyle();
unlockedCellStyle.setLocked(false);

/* cell which will be locked */
Cell lockedCell = sheet.createRow(0).createCell(0);
lockedCell.setCellValue("Hi, I'm locked...");
lockedCell.setCellStyle(lockedCellStyle);

/* unlocked cell */
Cell unlockedCell = sheet.createRow(1).createCell(0);
unlockedCell.setCellValue("Just edit me...");
unlockedCell.setCellStyle(unlockedCellStyle);

OutputStream out = new FileOutputStream("sample.xls");
workbook.write(out);
out.flush();
out.close();

答案 1 :(得分:2)

以下是一些经过测试的代码,可用于使特定单元格只读。根据您在@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

答案 2 :(得分:0)

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