gpt4 book ai didi

java - 如何使用 Apache POI 获取 Excel 文件中单元格的条件格式?

转载 作者:行者123 更新时间:2023-11-30 11:24:57 35 4
gpt4 key购买 nike

我有一个 xlsx 文件,其中已经有几个条件格式规则。如何从单元格中获取格式规则?我想“读取”现有单元格中的所有规则并将它们应用于我将创建的新规则

谢谢!

SheetConditionalFormatting rules = sheet.getSheetConditionalFormatting(); 
Cell cell = sheet.createRow(18).createCell(1);
CellReference cr = new CellReference(cell.getRowIndex(), cell.getColumnIndex());
CellRangeAddress[] range = {CellRangeAddress.valueOf("B19")};
ConditionalFormatting rule = rules.getConditionalFormattingAt(0);
rules.addConditionalFormatting(range, rule.getRule(0));

但我希望能够那样做:

cell.getFormattingRules();

我找到了答案。当我得到工作表中的所有规则时,我可以获得这些规则的范围。现在我需要检查一下,我的手机是否在这个范围内。感谢大家!

最佳答案

我有同样的要求,我用几个函数解决了它。如果您发现其中有任何错误,请告诉我。

它将条件格式样式从“styleCell”“复制”到“单元格”

    private void expandConditionalFormatting(XSSFCell cell, XSSFCell styleCell){
XSSFSheetConditionalFormatting xscf = cell.getSheet().getSheetConditionalFormatting();
for(int idx = 0;idx<xscf.getNumConditionalFormattings();idx++){
XSSFConditionalFormatting cf = xscf.getConditionalFormattingAt(idx);
List<CellRangeAddress> cra = Arrays.asList(cf.getFormattingRanges());
List<CellRangeAddress> newCra = new ArrayList();
for(CellRangeAddress c:cra){
if(containsCell(c, styleCell) && !containsCell(c,cell)){
newCra.add(new CellRangeAddress(Math.min(c.getFirstRow(), cell.getRowIndex()),Math.max(c.getLastRow(),cell.getRowIndex()),Math.min(c.getFirstColumn(), cell.getColumnIndex()),Math.max(c.getLastColumn(),cell.getColumnIndex())));
} else{
newCra.add(c);
}
}
ArrayList<XSSFConditionalFormattingRule> cfs = new ArrayList();
for(int ci=0;ci<cf.getNumberOfRules();ci++){
cfs.add(cf.getRule(ci));
}

xscf.addConditionalFormatting(newCra.toArray(new CellRangeAddress[newCra.size()]),cfs.toArray(new XSSFConditionalFormattingRule[cfs.size()]));
xscf.removeConditionalFormatting(idx);
}
}
private boolean containsCell(CellRangeAddress cra, Cell cell){
if(cra.getFirstRow()<=cell.getRowIndex() && cra.getLastRow()>=cell.getRowIndex()){
if(cra.getFirstColumn()<=cell.getColumnIndex() && cra.getLastColumn()>=cell.getColumnIndex()){
return true;
}
}
return false;
}

关于java - 如何使用 Apache POI 获取 Excel 文件中单元格的条件格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20501574/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com