String excelPath = "d:/test.xls";
HSSFWorkbook workbook = null;
try {
// XSSFWorkbook used for .xslx (>= 2007), HSSWorkbook for 03 .xsl
workbook = new HSSFWorkbook();// XSSFWorkbook();//WorkbookFactory.create(inputStream);
} catch (Exception e) {
System.out.println("创建Excel失败: ");
e.printStackTrace();
}
if (workbook != null) {
Sheet sheet = workbook.createSheet("测试数据");
Row row0 = sheet.createRow(0);
for (int i = 0; i < 6; i++) {
double test = 3000.0;
Cell cell = row0.createCell(i, Cell.CELL_TYPE_NUMERIC);
CellStyle cellStyle = workbook.createCellStyle();
HSSFDataFormat df = workbook.createDataFormat(); //此处设置数据格式
cellStyle.setDataFormat(df.getFormat("#,#0.0")); //小数点后保留两位,可以写contentStyle.setDataFormat(df.getFormat("#,#0.00"));
cell.setCellStyle(cellStyle);
cell.setCellValue( test );
}
try {
FileOutputStream outputStream = new FileOutputStream(excelPath);
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
System.out .println("写入Excel失败: ");
e.printStackTrace();
}
}
}}
public static void main(String[] args)
{
ExcelUtil eu = new ExcelUtil();
eu.testWriteExcel();
}
所以如果要达到要求就必须要设置cell的dataformat如上代码所示。
CellStyle cellStyle = workbook.createCellStyle();
HSSFDataFormat df = workbook.createDataFormat(); //此处设置数据格式
cellStyle.setDataFormat(df.getFormat("#,#0.0")); //小数点后保留两位,可以写contentStyle.setDataFormat(df.getFormat("#,#0.00"));
cell.setCellStyle(cellStyle);
这几行代码起了绝对的作用。最后结果如下图说是: