EXCEL输出可计算的数值类型
我这里的类型是BigDecimal,可根据自己的数字类型去判断
主要以下两行代码
cell.setCellValue(((BigDecimal) cellData).doubleValue()); // 输出double类型
dataStyle.setDataFormat(wb.createDataFormat().getFormat("0")); // 设置为整数 (显示小数可尝试"0.0")
private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
int colIndex;
Font dataFont = wb.createFont();
dataFont.setFontName("simsun");
dataFont.setFontHeightInPoints((short) 14);
dataFont.setColor(IndexedColors.BLACK.index);
XSSFCellStyle dataStyle = wb.createCellStyle();
dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
dataStyle.setFont(dataFont);
setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
for (List<Object> rowData : rows) {
Row dataRow = sheet.createRow(rowIndex);
dataRow.setHeightInPoints(25);
colIndex = 0;
for (Object cellData : rowData) {
Cell cell = dataRow.createCell(colIndex);
if (cellData != null) {
if(cellData instanceof BigDecimal) {
// 如果是BigDecimal,已数字格式输出, 并且设置单元格为可以计算的格式
cell.setCellValue(((BigDecimal) cellData).doubleValue());
dataStyle.setDataFormat(wb.createDataFormat().getFormat("0"));
}else {
cell.setCellValue(cellData.toString());
}
} else {
cell.setCellValue("");
}
cell.setCellStyle(dataStyle);
colIndex++;
}
rowIndex++;
}
return rowIndex;
}
本文介绍如何在EXCEL中将BigDecimal类型的数值转换为可计算的数字格式,并通过示例代码展示了如何设置单元格格式以确保数值正确显示。代码片段包括了如何创建字体样式、单元格样式以及如何根据不同数据类型进行单元格值的设置。
1631





