© Ptw-cwl
目录
文章目录
- 目录
- Excel清除表格条件格式规则
- 1.开始 -> 条件格式
- 2.条件格式 -> 清除规则
- 3.管理规则也能删除
- 代码
- 报java.lang.IllegalArgumentException: Specified CF index 43 is outside the allowable range (0..42)如何解决
- 源码
Excel清除表格条件格式规则
如何想看java代码部分如何实现的,可以直接跳到代码部分
1.开始 -> 条件格式
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vJoevPGI-1681979346482)(img/image-20230420162201265.png)]](https://img-blog.csdnimg.cn/914eafd5359c4e62808a100c962c3d01.png)
2.条件格式 -> 清除规则
具体是清除单个单元格的规则还是整个工作表的规则,这个根据自己的情况
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PPCUEgMr-1681979346483)(img/image-20230420162333747.png)]](https://img-blog.csdnimg.cn/565cc0a0d49c495db9e926e784039eae.png)
3.管理规则也能删除
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BGXnH9Ho-1681979346485)(img/image-20230420162420829.png)]](https://img-blog.csdnimg.cn/be7648eeb15640369ffe43bd6e98c2f2.png)
代码
//file.toPath() 文件的路径
XSSFWorkbook workbook = newXSSFWorkbook(Files.newInputStream(file.toPath()));
XSSFSheet sheet = workbook.getSheetAt(0);
//清除条件格式规则
XSSFSheetConditionalFormatting formatting = sheet.getSheetConditionalFormatting();
if (formatting != null) {
int numRules = formatting.getNumConditionalFormattings();
for (int index = numRules - 1; index >= 0; index--) {
//注意index要小于formatting.getNumConditionalFormattings()获取的值,要不然会报错
formatting.removeConditionalFormatting(index);
}
}
他这个for循环之所以这样写是因为我被坑过 …
报java.lang.IllegalArgumentException: Specified CF index 43 is outside the allowable range (0…42)如何解决
我原先也是写的正常的for循环,但是我一运行就报了个
java.lang.IllegalArgumentException: Specified CF index 43 is outside the allowable range (0..42)我还以为是我代码那里出了问题,然后排查了好大一会才找到问题
源码
public void removeConditionalFormatting(int index) {
this.checkIndex(index);
this._sheet.getCTWorksheet().removeConditionalFormatting(index);
}
private void checkIndex(int index) {
int cnt = this.getNumConditionalFormattings();
if (index < 0 || index >= cnt) {
throw new IllegalArgumentException("Specified CF index " + index + " is outside the allowable range (0.." + (cnt - 1) + ")");
}
}
通过源码我们可以发现调用了checkIndex才报错的,每次循环删除的时候this.getNumConditionalFormattings()的值就减少,然后就会导致报错,用上方代码的for循环就可以解决
可以通过调用
sheetCF.addConditionalFormatting()来添加新的条件格式规则,以根据需要定制您的工作簿。不过本文章不讲这方面的,后续如果写的话会过来推荐
Ptw-cwl



















