项目场景:
实际业务需求导出的复杂表格,要求金额保留两位小数,百分比导出后,不在手动转换成数值类型。
解决方案:
在ureport2 源码中 ExcelBuilderDirect 类中,修改如下代码:
if (obj instanceof String) {
//百分比转换数值类型,保留两位
if (String.valueOf(obj).contains("%")) {
Double b = Double.parseDouble(String.valueOf(obj).replace("%", "")) * 0.01; style.setDataFormat(df.getFormat("0.00%"));
cell.setCellStyle(style);
cell.setCellValue(b);
cell.setCellType(CellType.NUMERIC);
} else {
cell.setCellValue((String) obj);
cell.setCellType(CellType.STRING);
}
} else if (obj instanceof Number) {
//数值为整数,小数点保留两位
if (obj instanceof BigDecimal) {
Pattern pattern = Pattern.compile("[0-9]*");
boolean matches = pattern.matcher(String.valueOf(obj)).matches();
if (matches == true) {
style.setDataFormat(df.getFormat("0_ "));
} else {
style.setDataFormat(df.getFormat("0.00_ "));
}
}
cell.setCellStyle(style);
BigDecimal bigDecimal = Utils.toBigDecimal(obj);
cell.setCellValue(bigDecimal.doubleValue());
cell.setCellType(CellType.NUMERIC);
}......