jXLS 1.x的动态单元格样式有example,但我找不到比AreaListener this example更接近的内容。
我有一个非常基本的XLS生成模板,处理代码就像
一样简单context.putVar("headers", columns);
context.putVar("data", cells);
context.getConfig().setCellStyleMap();
JxlsHelper.getInstance().processTemplate(is, result, context);
如何添加一些允许我修改某些单元格样式的侦听器(比如为N字符长的文本添加自动换行,或者如果值是某种模式则更改背景颜色)?< / p>
答案 0 :(得分:2)
你可以像这样实现它
主要方法:
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的区域。在这种情况下,我只是从根区域遍历到每个指令区域,我希望突出显示支付超过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);
}