poi 启用保护后取消_使用Apache POI在受保护的工作表中启用过滤和排序

I have created a workbook with protected sheets because I only need a very few columns as editable. Although I want to let the user to be able to sort and filter columns.

Google searches have failed me as of yet. Any kind of help will be appreciated.

解决方案

If it is a XSSFSheet, then XSSFSheet.lockAutoFilter(false) and XSSFSheet.lockSort(false) will set the properties for enabling auto-filtering and sorting in protected sheets.

Of course the auto-filter itself must be set before protecting the sheet. The setting lockAutoFilter(false) does only enabling the usage the auto-filter in protected sheets.

And for using sorting there must be set a range which is enabled for users to edit. This is because while sorting the cell values will be changed since contents of rows and so of all cells in that rows probably must be exchanged while sorting.

In Excel GUI this is made via Review tab -> Allow Users to Edit Ranges. in apache poi we have to add a CTProtectedRange to the CTWorksheet.

Note the usage of CTProtectedRange needs the full jar of all of the schemas ooxml-schemas-1.3.jar as mentioned in faq-N10025.

Complete example:

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.*;

import org.apache.poi.ss.util.CellRangeAddress;

import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTProtectedRange;

import java.util.Arrays;

public class CreateExcelXSSFProtectedSheetAllowFilteringAndSorting {

public static void main(String[] args) throws Exception {

Workbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet();

Row row;

Cell cell;

row = sheet.createRow(0);

for (int c = 0 ; c < 4; c++) {

cell = row.createCell(c);

cell.setCellValue("Field " + (c+1));

}

for (int r = 1; r < 10; r++) {

row = sheet.createRow(r);

for (int c = 0 ; c < 4; c++) {

cell = row.createCell(c);

cell.setCellValue("Data R" + (r+1) + "C" + (c+1));

}

}

sheet.setAutoFilter(CellRangeAddress.valueOf("A1:D10"));

((XSSFSheet)sheet).lockAutoFilter(false);

CTProtectedRange protectedRange = ((XSSFSheet)sheet).getCTWorksheet()

.addNewProtectedRanges()

.addNewProtectedRange();

protectedRange.setName("enableSorting");

protectedRange.setSqref(Arrays.asList(new String[]{"A1:D10"}));

((XSSFSheet)sheet).lockSort(false);

sheet.protectSheet("");

for (int c = 0 ; c < 4; c++) {

sheet.autoSizeColumn(c);

}

FileOutputStream out = new FileOutputStream("CreateExcelXSSFProtectedSheetAllowFilteringAndSorting.xlsx");

workbook.write(out);

out.close();

workbook.close();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值