How to define dynamic cell range for Excel sheet using java?

白昼怎懂夜的黑 提交于 2021-01-29 09:49:12

问题


This is my code:

SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
ConditionalFormattingRule rule = sheetCF.createConditionalFormattingRule( "MOD(ROW() - 1, 1) = 0");
PatternFormatting fill = rule.createPatternFormatting();
style.setFillForegroundColor(IndexedColors.BLUE.index);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);

FontFormatting ffRed = rule.createFontFormatting();
ffRed.setFontColorIndex(IndexedColors.WHITE.index);

CellRangeAddress[] regions = {  CellRangeAddress.valueOf("A1:ZZ1") };

sheetCF.addConditionalFormatting(regions,rule);

ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(
                        "MOD(ROW() - 1, 2) = 0");

PatternFormatting fill1 = rule1.createPatternFormatting();
fill1.setFillBackgroundColor(IndexedColors.PALE_BLUE.index);
fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

CellRangeAddress[] regions1 = {  CellRangeAddress.valueOf("A2:ZZ8304") };

sheetCF.addConditionalFormatting(regions1,rule1);

Inside CellRangeAddress.values I gave static value. But I wanted it to be dynamic. That is wherever there's data present it should take range dynamically. How to resolve this issue? I referred to define dynamic cell range but it didn't work.


回答1:


You can try like this

String name = CellReference.convertNumToColString(cell.getColumnIndex());
    String location = "$" + name + "$" + cell.getRowIndex() + ":$" + name + "$" + (cell.getRowIndex() + 1);

    CellRangeAddress[] regions = { CellRangeAddress.valueOf(location) };


来源:https://stackoverflow.com/questions/59480696/how-to-define-dynamic-cell-range-for-excel-sheet-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!