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;
}