gpt4 book ai didi

excel - jXLS 2.3 - 添加监听器以根据单元格内容更新单元格样式?

转载 作者:行者123 更新时间:2023-12-04 19:48:11 40 4
gpt4 key购买 nike

有一个example jXLS 1.x 的动态单元格样式,但我找不到比 this example 更接近的东西对于 AreaListener。

我有一个非常基本的XLS生成模板,处理代码就这么简单

context.putVar("headers", columns);
context.putVar("data", cells);
context.getConfig().setCellStyleMap();
JxlsHelper.getInstance().processTemplate(is, result, context);

如何添加一些允许我修改某些单元格样式的监听器(例如为长度超过 N 个字符的文本添加自动换行,或者如果值具有特定模式则更改背景颜色)?

最佳答案

你可以这样实现

在主要方法中:

        try(InputStream is = HighlightDemo.class.getResourceAsStream("highlight_template.xls")) {
try (OutputStream os = new FileOutputStream("target/highlight_output.xls")) {
PoiTransformer transformer = PoiTransformer.createTransformer(is, os);
AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer, false);
List<Area> xlsAreaList = areaBuilder.build();
Area mainArea = xlsAreaList.get(0);
Area loopArea = xlsAreaList.get(0).getCommandDataList().get(0).getCommand().getAreaList().get(0);
loopArea.addAreaListener(new HighlightCellAreaListener(transformer));
Context context = new Context();
context.putVar("employees", employees);
mainArea.applyAt(new CellRef("Result!A1"), context);
mainArea.processFormulas();
transformer.write();
}
}

此示例中使用的模板与 Object Collection Demo 中的相同样本。最棘手的部分是找到您要应用 AreaListener 的区域。在这种情况下,我只是从根区域遍历到 EachCommand 区域,我希望在该区域突出显示付款超过 2000 的员工。

AreaListener 实现类似于 AreaListener example 中的实现

public class HighlightCellAreaListener implements AreaListener {
private final CellRef paymentCell = new CellRef("Template!C4")
...
public void afterTransformCell(CellRef srcCell, CellRef targetCell, Context context) {
System.out.println("Source: " + srcCell.getCellName() + ", Target: " + targetCell.getCellName());
if(paymentCell.equals(srcCell)){ // we are at employee payment cell
Employee employee = (Employee) context.getVar("employee");
if( employee.getPayment().doubleValue() > 2000 ){ // highlight payment when >= $2000
logger.info("highlighting payment for employee " + employee.getName());
highlightCell(targetCell);
}
}
}
private void highlightCell(CellRef cellRef) {
Workbook workbook = transformer.getWorkbook();
Sheet sheet = workbook.getSheet(cellRef.getSheetName());
Cell cell = sheet.getRow(cellRef.getRow()).getCell(cellRef.getCol());
CellStyle cellStyle = cell.getCellStyle();
CellStyle newCellStyle = workbook.createCellStyle();
newCellStyle.setDataFormat( cellStyle.getDataFormat() );
newCellStyle.setFont( workbook.getFontAt( cellStyle.getFontIndex() ));
newCellStyle.setFillBackgroundColor( cellStyle.getFillBackgroundColor());
newCellStyle.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
newCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cell.setCellStyle(newCellStyle);
}

关于excel - jXLS 2.3 - 添加监听器以根据单元格内容更新单元格样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42310928/

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