POI设置EXCEL单元格格式为文本、小数、百分比、货币、日期、科学计数法和中文大写
再读本篇文章之前,请先看我的前一篇文章,前一篇文章中有重点讲到POI设置EXCEL单元格格式为文本格式,剩下的设置小数、百分比、货币、日期、科学计数法和中文大写这些将在下面一一写出
以下将要介绍的每一种都会用到这三行中的变量
?
?? ? ? ? ? ?HSSFWorkbook demoWorkBook = new HSSFWorkbook(); ??
?? ? ? ? ? ?HSSFSheet demoSheet = demoWorkBook.createSheet("The World's 500 Enterprises"); ??
?? ? ? ? ? ?HSSFCell cell = demoSheet.createRow(0).createCell(0);
?
第一种:日期格式
?
?? ? ? ? ? ?cell.setCellValue(new Date(2008,5,5));
?? ? ? ? ? ?//set date format
?? ? ? ? ? ?HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
?? ? ? ? ? ?HSSFDataFormat format= demoWorkBook.createDataFormat();
?? ? ? ? ? ?cellStyle.setDataFormat(format.getFormat("yyyy年m月d日"));
?? ? ? ? ? ?cell.setCellStyle(cellStyle);
?
第二种:保留两位小数格式
?? ? ? ? ???cell.setCellValue(1.2);
?? ? ? ? ? ?HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
?? ? ? ? ? ?cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
?? ? ? ? ? ?cell.setCellStyle(cellStyle);
?
这里与上面有所不同,用的是HSSFDataFormat.getBuiltinFormat()方法,之所以用这个,是因为0.00是Excel内嵌的格式,完整的Excel内嵌格式列表大家可以看这个窗口中的自定义列表:
?这里就不一一列出了
?
第三种:货币格式
?
?? ? ? ? ? ?cell.setCellValue(20000);
?? ? ? ? ? ?HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
?? ? ? ? ? ?HSSFDataFormat format= demoWorkBook.createDataFormat();
?? ? ? ? ? ?cellStyle.setDataFormat(format.getFormat("¥#,##0"));
?? ? ? ? ? ?cell.setCellStyle(cellStyle);
?
第四种:百分比格式
?
?? ? ? ? ? ?cell.setCellValue(20);
?? ? ? ? ? ?HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
?? ? ? ? ? ?cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%"));
?? ? ? ? ? ?cell.setCellStyle(cellStyle);
??此种情况跟第二种一样
?
第五种:中文大写格式
?
?? ? ? ? ? ?cell.setCellValue(20000);
?? ? ? ? ? ?HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
?? ? ? ? ? ?HSSFDataFormat format= demoWorkBook.createDataFormat();
?? ? ? ? ? ?cellStyle.setDataFormat(format.getFormat("[DbNum2][$-804]0"));
?? ? ? ? ? ?cell.setCellStyle(cellStyle);
?
第六种:科学计数法格式
?
?? ? ? ? ? ?cell.setCellValue(20000);
?? ? ? ? ? ?HSSFCellStyle cellStyle = demoWorkBook.createCellStyle();
?? ? ? ? ? ?cellStyle.setDataFormat( HSSFDataFormat.getBuiltinFormat("0.00E+00"));
?? ? ? ? ? ?cell.setCellStyle(cellStyle);
此种情况也与第二种情况一样
1 楼 kesun_shy 2011-09-27 不错~用到了~