背景
最近项目需要实现数据的导出,并支持导入数据实现新增或更新数据
需求
- 隐藏列:因为需要更新数据,导出的excel需要保存记录ID。但又不希望用户看到
- 锁定ID数据:考虑到用户直接复制行导致隐藏列被复制,从而将新增的数据变成更新数据,将隐藏的列放在第一行并锁定则不能复制
- 删与增行:由于导入的数据存在合并行,用户编辑时会用到删除与新增行
实现
- 遇到的问题:由于excel被设置为保护模式后,除填充数据时可设置单元格为lock或unlock,默认都是lock的单元格,这将导致无法删除行
- 实现思路:通过wps新建一个sheet并使用Ctrl+A统一将单元格设置为unlock,最后使用java代码加载并填充单元格(根据要求设置lock或unlock样式)
思路主要来源(多谢博主分享)
具体代码
注意:需要填充数据的单元格,如果无需lock一定要设置对应的样式
// 第一步,通过加载template.xlsx创建一个HSSFWorkbook
XSSFWorkbook wb;
try {
InputStream is = ExcelUtil.class.getClassLoader().getResourceAsStream("template.xlsx");
wb = new XSSFWorkbook(is);
} catch (IOException e) {
throw new SystemException("找不到项目中的模板excel", e);
}
// 第二步,在workbook中编辑template的sheet
wb.setSheetName(0, sheetName);
XSSFSheet sheet = wb.getSheetAt(0);
sheet.createFreezePane(0, 1, 0, 1);
sheet.protectSheet("123456");
CTSheetProtection sheetProtection = sheet.getCTWorksheet().getSheetProtection();
sheetProtection.setSelectLockedCells(true);
sheetProtection.setSelectUnlockedCells(false);
sheetProtection.setFormatCells(false);
sheetProtection.setFormatColumns(false);
sheetProtection.setFormatRows(false);
sheetProtection.setInsertRows(false);
sheetProtection.setDeleteRows(false);
sheetProtection.setSort(false);
sheetProtection.setAutoFilter(false);
网友评论