2014-09-24 25 views
7

Ví dụ,Luôn luôn hiển thị hai điểm thập phân ở tế bào excel sử dụng Apache POI

XSSFCellStyle style=(XSSFCellStyle) workbook.createCellStyle(); 
style.setDataFormat(workbook.createDataFormat().getFormat("#.##")); 

productCell.setCellValue(12.4); 
productCell.setCellType(Cell.CELL_TYPE_NUMERIC); 
productCell.setCellStyle(style); 

này hiển thị 12.4 trong ô được xác định. Nó phải là 12.40. Giá trị 12 được hiển thị là 12. là điều không cần thiết.

Nếu giá trị là 0 thì giá trị đó sẽ hiển thị một dấu chấm .. Nó phải luôn luôn hiển thị hai chữ số thập phân - 0.00, trong trường hợp này bất kể giá trị được lưu trữ trong một ô.

Làm thế nào để buộc excel luôn hiển thị hai chữ số thập phân trong một ô số?


Tôi sử dụng một trong các kiểu sau để hiển thị ô số.

XSSFColor commonColor = new XSSFColor(new java.awt.Color(240, 240, 240)); 
XSSFColor cellBorderColour = new XSSFColor(new java.awt.Color(0, 76, 153)); 

Font font = workbook.createFont(); 
font.setBoldweight(Font.BOLDWEIGHT_BOLD); 
font.setColor(IndexedColors.DARK_BLUE.index); 

XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle(); 
style.setFillForegroundColor(commonColor); 
style.setFillPattern(CellStyle.SOLID_FOREGROUND); 
style.setAlignment(CellStyle.ALIGN_RIGHT); 
style.setFont(font); 

style.setBorderLeft(BorderStyle.HAIR); 
style.setBorderColor(XSSFCellBorder.BorderSide.LEFT, cellBorderColour); 
style.setBorderTop(BorderStyle.HAIR); 
style.setBorderColor(XSSFCellBorder.BorderSide.TOP, cellBorderColour); 
style.setBorderRight(BorderStyle.HAIR); 
style.setBorderColor(XSSFCellBorder.BorderSide.RIGHT, cellBorderColour); 
style.setBorderBottom(BorderStyle.DOUBLE); 
style.setBottomBorderColor(cellBorderColour); 

Tôi đã áp dụng một số công thức excel để thực hiện một số phép tính trên ô số sẽ được thực hiện sau khi áp dụng định dạng số (làm tròn một nửa) trên ô số.

+0

Bạn đã thử http://stackoverflow.com/questions/9789627/write-double-value-in-numeric-cell-with-specific-format-in-apache-poi-3-7 chưa? –

+0

Có hành vi chính xác giống như được đề cập trong câu hỏi. – Tiny

+0

Bạn cần sử dụng kiểu ô nào nếu bạn định dạng ô trong Excel, để làm cho nó trông như thế nào bạn muốn nó? – Gagravarr

Trả lời

19

Trong định dạng Excel, # có nghĩa là "đặt số ở đây chỉ khi cần", nhưng 0 có nghĩa là "luôn đặt số ở đây, ngay cả khi đó là 0 không cần thiết". Bạn có thể chỉ định the data format in Apache POI chính xác as you would in Excel itself. Nếu bạn muốn số 0 hiển thị, thì bạn cần sử dụng 0 s làm định dạng chữ số. Hãy thử

style.setDataFormat(workbook.createDataFormat().getFormat("0.00")); 

Điều này sẽ làm cho giá trị 0 hiển thị như 0.0012.4 như 12.40.

Các vấn đề liên quan