1. 程式人生 > >POI 導出excel帶小數點的數字格式顯示不對解決方法

POI 導出excel帶小數點的數字格式顯示不對解決方法

usermod 技術 cell double 小數 xls tco contents 我們

最近看到了一個問題就是java導出excel中帶小數點的數字顯示不對, 比如我想在excel中第一行顯示: 3,000.0 但是在excle中導出的格式總是不帶小數點 3000(非文本格式),而且也不是以金融格式顯示的。這時候我們的解決方法是要為單元格中的數字設置dataformat。代碼如下 import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; public class ExcelUtil { public void testWriteExcel() {

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

}
當沒設置format的時候,光設置CELL_TYPE_NUMERIC只能讓數字在excel中顯示為數字類型(非文本類型,而不能保證它小數位和金融格式(每位一個逗號)。 技術分享圖片

所以如果要達到要求就必須要設置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);

這幾行代碼起了絕對的作用。最後結果如下圖說是:

技術分享圖片

POI 導出excel帶小數點的數字格式顯示不對解決方法